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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With