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
{
using (File.Open(path, FileMode.CreateNew))
{
return true;
}
}
catch (IOException)
{
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. , .