Skip to content

Commit cd6a6a2

Browse files
committed
Fix duplicated filename bug
1 parent 8d42243 commit cd6a6a2

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

PrintScreen/Program.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ static String GetScreenshotName()
8888
Directory.CreateDirectory(path);
8989
path = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd_HH-mm-ss"));
9090
int num = 0;
91-
for (; File.Exists(Path.Combine(path, num == 0 ? "" : ("_" + num)) + ".png"); num++) ;
91+
for (; File.Exists(path + (num == 0 ? "" : ("_" + num)) + ".png"); num++) ;
9292
return path + (num == 0 ? "" : ("_" + num)) + ".png";
9393
}
9494

@@ -105,6 +105,9 @@ static String PrintScreen()
105105
Bitmap bmp = new Bitmap(bounds.Width, bounds.Height);
106106
using (Graphics g = Graphics.FromImage(bmp))
107107
g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size);
108+
// Since the program is single-threaded, race conditions won't happen
109+
// For multi-threaded program, use the following with try-catch can guarantee that no file is overwritten:
110+
// File.Open(path, FileMode.CreateNew)
108111
String name = GetScreenshotName();
109112
bmp.Save(name, ImageFormat.Png);
110113
return name;

0 commit comments

Comments
 (0)