System.IO.File.GetAttributes 方法

方法描述

获取在此路径上的文件的 FileAttributes。

语法定义(C# System.IO.File.GetAttributes 方法 的用法)

public static FileAttributes GetAttributes(
	string path
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
path System-String 该文件的路径。
返回值 System.IO.FileAttributes 路径上文件的 FileAttributes。

提示和注释

允许 path 参数指定相对或绝对路径信息。 相对路径信息被解释为相对于当前工作目录。 若要获取当前工作目录,请参见 GetCurrentDirectory。

有关通用 I/O 任务的列表,请参见通用 I/O 任务。

System.IO.File.GetAttributes 方法例子

下面的示例通过将 Archive 和 Hidden 特性应用于文件,演示了 GetAttributes 和 SetAttributes 方法。

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 exists.
        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;
    }
}

异常

异常 异常描述
ArgumentException path 为空,仅包含空白,或包含无效字符。
PathTooLongException 指定的路径、文件名或者两者都超出了系统定义的最大长度。 例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
NotSupportedException path 的格式无效。
FileNotFoundException path 表示一个文件且它是无效的,例如,位于未映射的驱动器上或无法找到文件。
DirectoryNotFoundException path 表示一个目录且它是无效的,例如,位于未映射的驱动器上或无法找到目录。
IOException 此文件正由另一个进程使用。
UnauthorizedAccessException 调用方没有所要求的权限。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。