【问题标题】:Why is the FileAttributes value for a file which does not exist -1?为什么不存在的文件的 FileAttributes 值为 -1?
【发布时间】:2016-09-05 12:59:48
【问题描述】:

考虑下面的代码 -

 FileInfo fileInfo = new FileInfo("C:\\doesNotExist.txt");
 Console.WriteLine(fileInfo.Attributes);
 Console.WriteLine(fileInfo.Attributes.HasFlag(FileAttributes.ReadOnly));

根据documentation,枚举的默认基础类型是int,而值为-1 的int 基本上是二进制的全1。由于 FileAttributes 允许其成员值 (as stated here) 的按位组合,为什么 FileAttributes 的默认值为 -1,因为这意味着不存在的文件拥有所有可能的 FileAttributes(上面的代码打印 True 第三行)

【问题讨论】:

  • 向后兼容。改用 File.GetAttributes(),它会抛出。

标签: c# fileinfo system.io.fileinfo


【解决方案1】:

这只是推测,来源令人困惑,但看起来可能是这样,因此代码可以区分尚未初始化的数据(即默认为零的 int)和已初始化的数据,但是没有价值,就像不存在的文件上的文件属性一样。

来自source code for File.FillAttributeInfo

// Returns 0 on success, otherwise a Win32 error code.  Note that
// classes should use -1 as the uninitialized state for dataInitialized.

如果找不到文件,则then

if (!returnErrorOnNotFound) {
    // Return default value for backward compbatibility
    dataInitialised = 0;
    data.fileAttributes = -1;
}

期望调用者在访问属性之前检查 FileInfo 的 Exists 属性是否为真似乎是合理的。

【讨论】:

    猜你喜欢
    • 2011-12-17
    • 2012-06-20
    • 2011-07-15
    • 1970-01-01
    • 2015-08-28
    • 2017-06-19
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多