Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Append Number To File Being Saved

I have created a screenshot program and all is working great. The only problem is, I am not sure how I can make it so the screenshots are saved with appending numbers.

Example: Screenshot 1, Screenshot 2, Screenshot 3, Screenshot 4, etc.

Obviously this could be applied to other files being saved. Any ideas? Thank you.

like image 410
user Avatar asked Oct 08 '09 00:10

user


2 Answers

Here is a method I use frequently for this very case. Just pass in a string like "Screenshot" and it will find the lowest available filename in the format of "Screenshot [number]" (or just "Screenshot" if there aren't any already):

private string GetUniqueName(string name, string folderPath)
{
    string validatedName = name;
    int tries = 1;
    while (File.Exists(folderPath + validatedName))
    {
        validatedName = string.Format("{0} [{1}]", name, tries++);
    }
    return validatedName;
}

(Note: this is a slightly simplified version that doesn't take file extensions into account).

like image 196
Rex M Avatar answered Sep 19 '22 12:09

Rex M


Is there a reason you're using numbers? Will the same folder be re-used later for another session? Should the numbers restart and replace existing files if the day is different?

These are the sorts of things to keep in mind. It's worth noting that OS X used to provides "Picture 1", "Picture 2" when doing screenshots, and thankfully in the new version it now uses "Screenshot taken on 2009-12-08 at 11.35.12" or something similar, allowing easier sorting by date, easily avoiding naming conflicts etc.

As posted in other suggestions you still need to do a check if the file already exists, and when you retry DateTime.Now will be different so the filename would be different. Of course you shouldn't get any conflicts unless the screenshots are in the same millisecond or the user is messing with the date/time (or daylight savings can mess you up too).

like image 30
Timothy Walters Avatar answered Sep 20 '22 12:09

Timothy Walters