I find myself doing this a lot just to ensure the filename is not in use. Is there a better way?
Directory.Exists(name) || File.Exists(name)
Sure :)
internal static bool FileOrDirectoryExists(string name)
{
return (Directory.Exists(name) || File.Exists(name));
}
bool FileOrDirectoryExists(string path)
{
try
{
File.GetAttributes(_source);
}
catch (FileNotFoundException)
{
return false;
}
return true;
}
How about checking whether FileAttributes == -1?
public static bool PathExists(this string path) {
DirectoryInfo dirInfo = null;
try { dirInfo = new DirectoryInfo(path.TrimEnd(Path.DirectorySeparatorChar)); }
catch { }
if (dirInfo == null || dirInfo.Attributes == (FileAttributes)(-1))
return false;
return true;
}
Another way to check if file exist.
FileInfo file = new FileInfo("file.txt");
if (file.Exists)
{
// TO DO
}
You can use following function:
[DllImport("shlwapi", EntryPoint = "PathFileExists", CharSet = CharSet.Unicode)]
public static extern bool PathExists(string path);
My way of checking this is using the FileSystemInfo, here is my code:
FileSystemInfo info =
File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory) ?
new DirectoryInfo(data.Path) : (FileSystemInfo)new FileInfo(data.Path);
return info.Exists;