-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
We should implement the code for this internally and look at adding a public API for it. Probably Path.Exists(string path).
The internal helper should avoid any sort of path validation/normalization if possible. A bad path, by definition, doesn't exist. At least on the Windows side pre normalizing isn't needed (and wasteful). We should also consider exposing overloads such as Path.Exists(string path, bool normalize) to allow users to skip this as well (or perhaps a config switch).
[added by @danmoseley --]
Background and motivation
It's fairly common to want to know whether a file path is available to write to, without writing the file. For example, in order to prompt the user for a default save file name. In order to do this using our standard API, one must separately check whether the path matches an existing file, or an existing directory:
if (File.Exists(path) || Directory.Exists(path))
{
// choose another name, bail out, etc
}A new API can unify both these checks into one call, which is less verbose but more importantly potentially more efficient -- the underlying implementation (eg lstat, GetFileAttributesEx) generally returns all this info with a single call. While it's likely caching at some layer below .NET means that the above will not cause two disk reads, there's certainly inefficiency in performing two syscalls to get the same information.
API Proposal
public static partial class Path
{
// Implementation is logically equivalent to File.Exists(path) || Directory.Exists(path)
public static bool Exists([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] string? path) { .... };
}API Usage
if (Path.Exists(path))
{
// choose another name, bail out, etc
}Alternative Designs
There is already an abstract method FileSystemInfo.Exists which but to make that useable, it would have to change from abstract to virtual, as would the FileSystemInfo class, which would also need to expose a public constructor. This would also change its nature from representing either a directory or file (chosen at construction time) to representing something that is possibly either. As an instance method it would require newing up an object, which is wasteful. Finally, FileSystemInfo.Exists is likely less discoverable and readable than Path.Exists and discoverability is important since this is a fairly basic operation.
Risks
"Paths" in the broadest sense can represent more than traditional files and directories, and Path.Exists might imply to some that it could for example on Windows be used to test for the existence of a named pipe or other OS object. I suspect that is unlikely though, as the overwhelming use of the Path class is not with such objects.