Right now I have this code:
int number = 0;
DirectoryInfo di = new DirectoryInfo(scpath + @"Screenshots\");
if (di.Exists) {
} else {
di.Create();
}
int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
bmpScreenShot.Save(di + "Screenshot_" + number, ImageFormat.Jpeg);
Program takes a screenshot (which works) and saves it. What I want to do is to have the program check and see if a screenshot exists ("Screenshot_*") and to create it if it doesn't. If it does, increment file name till it hits a number that hasn't been used at the end of "Screenshot_" Not sure how to go about this given that it's more with files and incrementing. I'm thinking about a for loop but I'm playing with it now.
Getting the name of a file that does not exist sounds like a job for a method.
string IndexedFilename(string stub, string extension)
{
int ix = 0;
string filename = null;
do {
ix++;
filename = String.Format("{0}{1}.{2}", stub, ix, extension);
} while (File.Exists(filename));
return filename;
}
There is a race condition if you call this from multiple threads. Assuming you have just one app and one thread in the app asking for filenames, then this ought to work.
The code to use the method looks like this:
string di = Path.Combine(scpath, "Screenshots");
if (!Directory.Exists(di) {
Directory.Create(di);
}
int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
string filename = IndexedFilename(Path.Combine(di,"Shot_"),"jpg");
bmpScreenShot.Save(filename, ImageFormat.Jpeg);
Like @Quintin said, use datetime for filename:
string filename = Path.Combine(
di.FullName,
String.Format("{0}.jpg", DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss")));
bmpScreenShot.Save(filename, ImageFormat.Jpeg);
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