elbarae
elbarae

Reputation: 31

Crash when replacing existing image

I've been Working on a c# program that takes a screenshot every second, but it always crashes after the second screenshot.

pic of the error

I guess it's maybe because it fails to save the image as the name was already taken by the previous screenshot.

it crashes at this line exactly :

screenshot.Save("Screenshot.png", ImageFormat.Png);

I want it to overwrite the image every time without any crashes.

Upvotes: 2

Views: 90

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30655

You can use below code for replacing already created file, but be sure that you have already released previous file handle. If you use using like the code below, the operation for disposing thus releasing file handle is done automatically

using(FileStream fs = new FileStream(filePath, FileMode.Create,  
   FileAccess.ReadWrite, FileShare.None)
{
    image.Save(fs, ImageFormat.Png) //example format for saving file
}

Upvotes: 4

Related Questions