File.SetAttributes(String, FileAttributes) Método

Definição

Define o especificado FileAttributes do ficheiro no caminho especificado.

public:
 static void SetAttributes(System::String ^ path, System::IO::FileAttributes fileAttributes);
public static void SetAttributes(string path, System.IO.FileAttributes fileAttributes);
static member SetAttributes : string * System.IO.FileAttributes -> unit
Public Shared Sub SetAttributes (path As String, fileAttributes As FileAttributes)

Parâmetros

path
String

O caminho para o ficheiro.

fileAttributes
FileAttributes

Uma combinação bit a bit dos valores de enumeração.

Exceções

.NET Framework e .NET Core versões anteriores à 2.1: path está vazio, contém apenas espaços em branco, contém caracteres inválidos ou o atributo do ficheiro é inválido.

O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.

path está num formato inválido.

O caminho especificado é inválido (por exemplo, está num disco não mapeado).

O ficheiro não pode ser encontrado.

path especificou um ficheiro que é apenas leitura.

-ou-

Esta operação não é suportada na plataforma atual.

-ou-

path especificava um diretório.

-ou-

O interlocutor não tem a permissão necessária.

Exemplos

O exemplo seguinte demonstra os GetAttributes métodos e SetAttributes aplicando os Archive atributos e Hidden a um ficheiro.

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Create the file if it does not exist.
        if (!File.Exists(path))
        {
            File.Create(path);
        }

        FileAttributes attributes = File.GetAttributes(path);

        if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
        {
            // Show the file.
            attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
            File.SetAttributes(path, attributes);
            Console.WriteLine("The {0} file is no longer hidden.", path);
        }
        else
        {
            // Hide the file.
            File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
            Console.WriteLine("The {0} file is now hidden.", path);
        }
    }

    private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
    {
        return attributes & ~attributesToRemove;
    }
}
open System.IO
open System.Text

let removeAttribute attributes attributesToRemove = attributes &&& ~~~attributesToRemove

let path = @"c:\temp\MyTest.txt"

// Create the file if it does not exist.
if File.Exists path |> not then
    File.Create path |> ignore

let attributes = File.GetAttributes path

if attributes &&& FileAttributes.Hidden = FileAttributes.Hidden then
    // Show the file.
    let attributes =
        removeAttribute attributes FileAttributes.Hidden

    File.SetAttributes(path, attributes)
    printfn $"The {path} file is no longer hidden."
else
    // Hide the file.
    File.SetAttributes(path, File.GetAttributes path ||| FileAttributes.Hidden)
    printfn $"The {path} file is now hidden."
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        ' Create the file if it does not exist.
        If File.Exists(path) = False Then
            File.Create(path)
        End If

        Dim attributes As FileAttributes
        attributes = File.GetAttributes(path)

        If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
            ' Show the file.
            attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
            File.SetAttributes(path, attributes)
            Console.WriteLine("The {0} file is no longer hidden.", path)
        Else
            ' Hide the file.
            File.SetAttributes(path, File.GetAttributes(path) Or FileAttributes.Hidden)
            Console.WriteLine("The {0} file is now hidden.", path)
        End If
    End Sub

    Public Shared Function RemoveAttribute(ByVal attributes As FileAttributes, ByVal attributesToRemove As FileAttributes) As FileAttributes
        Return attributes And (Not attributesToRemove)
    End Function
End Class

Observações

O path parâmetro pode especificar informação relativa ou absoluta do caminho. A informação relativa do caminho é interpretada como relativa ao diretório de trabalho atual. Para obter o diretório de trabalho atual, veja GetCurrentDirectory.

Certos atributos do ficheiro, como Hidden e ReadOnly, podem ser combinados. Outros atributos, como Normal, devem ser usados isoladamente.

Não é possível alterar o estado de compressão de um File objeto usando o SetAttributes método.

Para uma lista de tarefas comuns de E/S, consulte Tarefas Comuns de E/S.

Aplica-se a

Ver também