开发者

Increment filename [duplicate]

This question already has answers here: How would you make a unique filename by adding a number? (22 answers) Closed 6 months ago.

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开发者_如何学Go 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);


If you are not worried about the rest of the file name (except the starting as "myFile", then you can simply create a GUID and concat it to the worg "myFile". This is the simplest way. The other way might be taking the syste ticks and add it as a string to the word "myFile".


If you construct your filenames so that they sort alphabetically

base000001
base000002
...
base000997

Then you can get a directory listing and just go to the end of the list to find the last file.

Be careful though: what happens if two instances of your program are running at the same time? There's a little window of opportunity between the test for the file existing and its creation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜