How can I try to create a file and return a value indicating whether it was created or not?

I am looking for something similar to something that will have a signature like this:

static bool TryCreateFile(string path);

This should avoid possible race conditions for threads, processes, and even other machines accessing the same file system, without requiring the current user to have more permissions than is necessary for File.Create. I currently have the following code that I don't particularly like:

static bool TryCreateFile(string path)
{
    try
    {
        // If we were able to successfully create the file,
        // return true and close it.
        using (File.Open(path, FileMode.CreateNew))
        {
            return true;
        }
    }
    catch (IOException)
    {
        // We want to rethrow the exception if the File.Open call failed
        // for a reason other than that it already existed.
        if (!File.Exists(path))
        {
            throw;
        }
    }

    return false;
}

Is there any other way to do this that I am missing?

, "" , , , . , :

static string GetNextFileName(string directoryPath)
{
    while (true)
    {
        IEnumerable<int?> fileNumbers = Directory.EnumerateFiles(directoryPath)
                                                 .Select(int.Parse)
                                                 .Cast<int?>();
        int nextNumber = (fileNumbers.Max() ?? 0) + 1;
        string fileName = Path.Combine(directoryPath, nextNumber.ToString());
        if (TryCreateFile(fileName))
        {
            return fileName;
        }
    }
}

Edit1. , .

+5
3

, .

,

if (File.Exists(fName))
   var s = File.OpenRead(fname);

, FileNotFound.

, :

,

System.IO.Path.GetRandomFileName(). , WinAPI, ..

+3

:

    private bool TryCreateFile(string path)
    {
        try
        {
            FileStream fs = File.Create(path);
            fs.Close();
            return true;
        }
        catch 
        {
            return false;
        }
    }

, . .

+1

.

- . TryCreateFile, , - , File.Exists? .

-

""

, . GUID, :

private static void Main(string[] args)
{
    var z = GetNextFileName(@"c:\temp");

    Console.ReadLine();
}

public static string GetNextFileName(string directoryPath)
{
    // Gets file name
    string fileName = Guid.NewGuid().ToString();
    string filePath = Path.Combine(directoryPath, fileName);

    // Creates an empty file
    using (var z = File.Open(filePath, FileMode.CreateNew))
    {
    }

    return filePath;
}

EDIT: , , GUID , . GUID 100% ?

0
source

All Articles