Jump to content

Overwrite an Image

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
vandel212

vandel212

    Newbie

  • Members
  • Pip
  • 1 posts
I'm trying to save an image over a file with the same file name. When it attempts to do this is bombs out because it says either it's a general GDI+ error or the process is already in use. This makes perfect sense why it would throw those errors, but how can I overwrite the file so that it doesn't give me this problem. I've tried Opening a file stream around it then closeing it, useing the bmpPicture.Dispose(), and I've tried the GC.Collect(), those didn't work. Is there something else I could try? or perhaps something I'm doing wrong?

here is a snippet of my code where it bombs out on me:

private void SaveFile()

        {

                // Set the bitmap object to the size of the screen

                bmpPicture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);

                // Create a graphics object from the bitmap

                gfxScreenShot = Graphics.FromImage(bmpPicture);

                // Take the screenshot from the upper left corner to the right bottom corner

                gfxScreenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y + 25, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

                // Save the screenshot to the specified path that the user has chosen                 

                bmpPicture.Save(FilePath, ImageFormat.Bmp); //****THIS IS WHERE THE ERROR IS THROWN****

        }


#2
ArekBulski

ArekBulski

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,376 posts
Well, if saving a file is not a problem, but overriding is, then just delete the file first. Here is some code.

Note that File.Delete method does not throw an exception if it was already deleted. Therefore you do not need any IF checking.

File.Delete("file");


#3
cdg10620

cdg10620

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 389 posts
ArekBulski is correct. You may want to have a statement checking to see if the file exists. If it does then delete it before saving, if not then just create. Just because you as the programmer knows that a file exists does not mean that the file will always exist. It's good practice to try and think of all situations to stop future errors.

if( file.exists( "fileName" ) )
{
     file.delete( "fileName" );
     file.save( "newFile" );
}
else
{
     file.save( "newFile" );
}

-CDG10620
Software Developer