dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.03k stars 4.67k forks source link

Incorrect value provided by DirectoryInfo.Attributes when directory does not exist #108345

Open DWAK-ATTK opened 2 hours ago

DWAK-ATTK commented 2 hours ago

Description

When DirectoryInfo.Exists is false, DirectoryInfo.Attributes == -1.

However, DirectoryInfo.Attributes is an enum (FileAttributes) with the [Flags] attribute applied. So when you do DirectoryInfo.Attributes.HasFlag(any flag value here) on a directory that doesn't exist, HasFlag(...) always returns true. But since the directory does not exist, a more correct result would be false.

Of course we can check Exists before Attributes.HasFlag(), but that seems more like a workaround and something that should be handled by the library.

Rather than setting DirectoryInfo.Attributes == -1, perhaps make it == 0 (zero; FileAttributes.None)

Reproduction Steps

DirectoryInfo dir = new DirectoryInfo(@"J:\hot-potato\something-that-will-never-exist");
bool exists = dir.Exists;    // false
bool isEncrypted = dir.Attributes.HasFlag(FileAttributes.encrypted);  // true

Expected behavior

DirectoryInfo.Attributes.HasFlag(...) should return false if the directory does not exist.

Actual behavior

It returns true.

Regression?

No idea.

Known Workarounds

Check the Directory.Info.Exists property fist.

Configuration

dotnet 8.0 on Windows 11

Other information

No response

dotnet-policy-service[bot] commented 2 hours ago

Tagging subscribers to this area: @dotnet/area-system-io See info in area-owners.md if you want to be subscribed.