开发者

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.


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


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


Here is a refined solution initially proposed by Rex M. It will generate file names as was asked in the actual question:

public string GetUniqueName(string name, string folderPath)
{
    string pathAndFileName = Path.Combine(folderPath, name);
    string validatedName = name;
    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(pathAndFileName);
    string ext = Path.GetExtension(pathAndFileName);
    int count = 1;
    while(File.Exists(Path.Combine(folderPath, validatedName)))
    {
        validatedName = string.Format("{0}{1}{2}",
            fileNameWithoutExt,
            count++,
            ext);
    }
    return validatedName;
}

You should always be using the Path.Combine function instead of doing string based concatenation to avoid errors on the hosting server. You never know how the web site will be hosted - subdomain, root site etc.


Since you are writing the files, one approach is to search the current save directory and find the newest file called ScreenshotXX, and use a regex to get the number from the name.

You could use the DirectoryInfo class along with the Regex class for this.


summary of solution

  1. Directory.GetFiles(dest);
  2. Sort files names
  3. analyze last file name , find the last number you used
  4. write next file with the next number appended to it.

would this work for you ?


This is what i use:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string newPath; List<string> files = new List<string>(Directory.GetFiles(path,"*.txt",SearchOption.TopDirectoryOnly)); for(int i=0; files.Contains(newPath=string.Format(path + @"\textfile{0}.txt",i)); i++) { Console.WriteLine("File:{0} exist skipping....", newPath); } File.WriteAllText(newPath,"dummy");

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜