1

Consider the below code -

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

As per the documentation, the default underlying type for an enumeration is int and an int with a value of -1 is basically all 1s in binary. Since, FileAttributes allows a bitwise combination of its member values (as stated here), why is the default value for FileAttributes -1 as it would mean that a file which does not exist possesses all possible FileAttributes (the above code prints True for the third line)

1 Answers1

1

This is only conjecture and the source is confusing, but it looks like it may be so the code can tell the difference between data which has not been initialized - i.e. an int defaulting to zero - and data which has been initialized, but has no value, like the file attributes on a non-existent file.

From the 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.

And then if the file is not found:

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

It seems reasonable to expect callers to check that the FileInfo's Exists property is true before accessing the attributes.

stuartd
  • 70,509
  • 14
  • 132
  • 163