File.GetAttributes Метод

Определение

Перегрузки

Имя Описание
GetAttributes(SafeFileHandle)

Возвращает указанный FileAttributes файл или каталог, связанный с fileHandle.

GetAttributes(String)

FileAttributes Возвращает файл по пути.

GetAttributes(SafeFileHandle)

Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
File.cs

Возвращает указанный FileAttributes файл или каталог, связанный с fileHandle.

public:
 static System::IO::FileAttributes GetAttributes(Microsoft::Win32::SafeHandles::SafeFileHandle ^ fileHandle);
public static System.IO.FileAttributes GetAttributes(Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle);
static member GetAttributes : Microsoft.Win32.SafeHandles.SafeFileHandle -> System.IO.FileAttributes
Public Shared Function GetAttributes (fileHandle As SafeFileHandle) As FileAttributes

Параметры

fileHandle
SafeFileHandle

Файл SafeFileHandle или каталог, для которого извлекаются атрибуты.

Возвращаемое значение

Файл FileAttributes или каталог.

Исключения

fileHandle равно null.

Вызывающий объект не имеет требуемого разрешения.

Применяется к

GetAttributes(String)

Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
File.cs
Исходный код:
File.cs

FileAttributes Возвращает файл по пути.

public:
 static System::IO::FileAttributes GetAttributes(System::String ^ path);
public static System.IO.FileAttributes GetAttributes(string path);
static member GetAttributes : string -> System.IO.FileAttributes
Public Shared Function GetAttributes (path As String) As FileAttributes

Параметры

path
String

Путь к файлу.

Возвращаемое значение

Файл FileAttributes по пути.

Исключения

.NET Framework и .NET Core версии старше 2.1: path пуст, содержит только пробелы или содержит недопустимые символы.

Указанный путь, имя файла или оба превышают определенную системой максимальную длину.

path имеет недопустимый формат.

path представляет файл и недействителен, например на несопоставленном диске или не удается найти файл.

path представляет каталог и недействителен, например на несопоставленном диске или не удается найти каталог.

Этот файл используется другим процессом.

Вызывающий объект не имеет требуемого разрешения.

Примеры

В следующем примере показаны GetAttributes методы и SetAttributes методы путем применения Archive атрибутов к Hidden файлу.

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

Комментарии

Параметр path может указывать относительные или абсолютные сведения о пути. Относительные сведения о пути интерпретируются как относительные к текущему рабочему каталогу. Чтобы получить текущий рабочий каталог, см. GetCurrentDirectory.

Список распространенных задач ввода-вывода см. в разделе Распространенные задачи ввода-вывода.

См. также раздел

Применяется к