views:

52

answers:

3
+1  Q: 

Increment filename

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

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".

Kangkan
+2  A: 

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.

djna
+1  A: 

Already there is an answer for a simliar question: http://stackoverflow.com/questions/1078003/c-how-would-you-make-a-unique-filename-by-adding-a-number

Victor Marzo