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)
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))
}
I think thats the only way. I generally have a "FileManager" class which have static methods encapsulating IO methods including the ones you indicated and then use that "FileManager" across all the applications as a library.
Another way to check if file exist.
FileInfo file = new FileInfo("file.txt");
if (file.Exists)
{
// TO DO
}
Note that the fact that you are using Exists() to check for file or directory name in use is subject to race conditions.
At any point after your Exists() test has passed, something could have created a file with that name before your code reaches the point where you create a file, for example.
(I'm assuming it is an exceptional condition for the file to already exist).
It is more reliable to simply to open the file, specifying an appropriate FileShare parameter.
Example:
using System;
using System.IO;
static class FileNameInUse
{
static void Main(string[] args)
{
string path = args[0];
using (var stream = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
// Write to file
}
}
}
So simply handling the IOException on failure may result in simpler code less prone to race conditions, because now:
FileMode.CreateNew
will cause an IOException
to be thrownFileShare.None
, no other process can access the file until you close it.Unfortunately, it is not possible to check whether a file is currently in use, and not throw an exception, without some ugly P/Invoke:
bool IsFileInUse(string fileName)
{
IntPtr hFile = Win32.CreateFile(fileName, Win32.FILE_READ_DATA, 0, IntPtr.Zero, Win32.OPEN_EXISTING, Win32.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
if (hFile.ToInt32() == Win32.INVALID_HANDLE_VALUE)
return true;
Win32.CloseHandle(hFile);
return false;
}
class Win32
{
const uint FILE_READ_DATA = 0x0001;
const uint FILE_SHARE_NONE = 0x00000000;
const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
const uint OPEN_EXISTING = 3;
const int INVALID_HANDLE_VALUE = -1;
[DllImport("kernel32.dll", SetLastError=true)]
internal static extern IntPtr CreateFile(string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll")]
internal static extern bool CloseHandle(IntPtr hObject);
}
And this fast check is also prone to race conditions, unless you return the file handle from it, and pass that to the relevant FileStream
constructor.