Search code examples
c#.netsequencefilenames

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.


Solution

  • 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).