2017-06-27 53 views
1

目前我的代碼能夠捕捉圖像並保存在指定位置,但如果我在第二次嘗試相同時,圖像被覆蓋,所以如果該文件夾中存在相同的文件名,我們必須動態更改文件的名稱。 我該怎麼做?C#:捕獲多個圖像並保存在同一個文件夾中?

當前屏幕捕捉的代碼是:

private void CaptureMyScreen() 
{ 
    try 
    { 
     //Creating a new Bitmap object 
     Bitmap captureBitmap = new Bitmap(1024, 768, PixelFormat.Format32bppArgb); 

     //Creating a Rectangle object which will capture our Current Screen 
     Rectangle captureRectangle = Screen.AllScreens[0].Bounds; 

     //Creating a New Graphics Object 
     Graphics captureGraphics = Graphics.FromImage(captureBitmap); 

     //Copying Image from The Screen 
     captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size); 

     //Saving the Image File (I am here Saving it in My D drive). 
     captureBitmap.Save(@"D:\Capture.jpg", ImageFormat.Jpeg); 

     //Displaying the Successfull Result 

     MessageBox.Show("Screen Captured"); 
    } 

    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
} 
+0

首先,從來沒有硬編碼在你的CS文件的路徑和文件名。嘗試追加一個GUID到文件名。 – Praveen

回答

4

您可以使用GUID爲每個捕獲文件獲得唯一的名稱。像

string guid = Guid.NewGuid().ToString(); 
captureBitmap.Save(@"D:\Capture-" + guid + ".jpg",ImageFormat.Jpeg); 

,或者使用的東西當前日期和時間,像這樣:

所有的
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); 
captureBitmap.Save(@"D:\Capture-" + timestamp + ".jpg",ImageFormat.Jpeg); 
相關問題