I want to create algorithm, to generate name for new file which I want to add to main directory. All files in this directory must has unique name and start with "myFile"
What do you think about this algorithm ? Can I optimize it ?
string startFileName="myFile.jpg";
string startDirectory="c:\MyPhotosWithSubFoldersAndWithFilesInMainDirectory";
bool fileWithThisNameExists = false;
string tempName = null;
do
{
tempName = startFileName +"_"+ counter++ + Path.GetExtension(startFileName);
foreach (var file in Directory.GetFiles(startDirectory)
{
if (Path.GetFileName(tempName) == Path.GetFileName(file))
{
fileWithThisNameExists = true;
}
}
if (fileWithThisNameExists) continue;
foreach (var directory in Directory.GetDirectories(startDirectory))
{
foreach (var file in Directory.GetFiles(directory))
{
if (Path.GetFileName(tempName) == Path.GetFileName(file))
{
fileWithThisNameExists = true;
}
}
}
} while (fileWithThisNameExists);