tags:

views:

132

answers:

4

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)
+6  A: 

Sure :)

internal static bool FileOrDirectoryExists(string name)
{
   return (Directory.Exists(name) || File.Exists(name))
}
PaulG
Extension method for Path class? "Performs operations on String instances that contain file or directory path information."
Si
Si. semi good idea for having it in a string instance. its really to bad .NET doesnt allow extending a static class :(
acidzombie24
I don't see this logic ever changing. Why make an extension method when you can just use the body of it for the check each time? Seems like overkill.
Ed Swangren
+2  A: 

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.

ydobonmai
+3  A: 

Another way to check if file exist.

FileInfo file = new FileInfo("file.txt");

if (file.Exists)
{
    // TO DO
}
In The Pink
I doubt why I get down vote for this answer?
In The Pink
Look at the tags before you post an answer.
lsalamon
Tag is C# , .NET and file. This is C# code and it can yield desired output.
In The Pink
+1 to even this out. weird that anyone would downvote :|. actually, not to even out. i would upvote this anyways. interesting and good answer.
acidzombie24
+5  A: 

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:

  • If something else has already created the file, FileMode.CreateNew will cause an IOException to be thrown
  • If your open and create succeeds, because of FileShare.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.

Leon Breedt
For some reason people never seem to get recognized for solving the problem, only for answering the question. +1 for answering the question that SHOULD have been asked.
Ben Voigt
+1. @Ben Voigt: Well theres no way for anyone to know the problem since i specified it BUT my question is WHAT I WANTED TO KNOW. I am actually using .Exist to check if my app created a temp folder (which it searches for a nonexisting folder and creates one then passing the name). I could just do a try{Directory.Delete()}catch but i prefer exist for convince. Under no circumstance should anything other then my app delete the folder. The folder is renamed once succeeded. So Leon actually didnt solve my problem.
acidzombie24
@Ben Voigt: actually i was wrong. In that case i use Directory.delete but when i create the directory i use that line to check if it exist then i use either Directory.CreateDirectory or file.open with the return filename. I use the function to generate the unique name in a specific format.
acidzombie24
@Ben: Thanks for the kind words, but I was just taking a guess. I've been bitten in the past by this type of thing, and thought I recognized a potential problem :)
Leon Breedt
+1 @Leon - For "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.."
ydobonmai