Search code examples
c#vb.netbitmapfilepathinputbox

C#: error when saving an image to the Documents folder


I have an image displaying on my C# form. When the user clicks "Save Image" button it pops up a Visual Basic input box. I am trying to add functionality to my form which allows the user to save the image when they enter the name of the image through the visual basic input box.

First, I added this code,

private void save_image(object sender, EventArgs e)
    {
        String picname;
        picname = Interaction.InputBox("Please enter a name for your Image");            
        pictureBit.Save("C:\\"+picname+".Png");                      
        MessageBox.Show(picname +" saved in Documents folder");
    } 

However, when I run the program and click the save button it gives this exception: "An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll"

Then I added few changes to the code to make it look like this,

private void save_image(object sender, EventArgs e)
    {

        SaveFileDialog savefile = new SaveFileDialog();            
        String picname;           
        picname = Interaction.InputBox("Please enter a name for your Image");
        savefile.FileName = picname + ".png";
        String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        using (Stream s = File.Open(savefile.FileName, FileMode.Create))
        {
            pictureBit.Save(s, ImageFormat.Png);
        }
        //pictureBit.Save("C:\\pic.Png");           
        MessageBox.Show(picname);                                
    }

When I run this code, it doesn't give the exception anymore but it saves the image in my c#->bin->debug folder. I know this might not be the ideal way of doing it but how do I set it's path so it saves the image in the documents folder.


Solution

  • String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    savefile.FileName = path + "\\" + picname + ".png";
    

    Other working example with show dialog:

    SaveFileDialog savefile = new SaveFileDialog();
    String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    
    savefile.InitialDirectory = path;
    savefile.FileName = "picname";
    savefile.Filter = "PNG images|*.png";
    savefile.Title = "Save as...";
    savefile.OverwritePrompt = true;
    
    if (savefile.ShowDialog() == DialogResult.OK)
    {
        Stream s = File.Open(savefile.FileName, FileMode.Create);
        pictureBit.Save(s,ImageFormat.Png);
        s.Close();
    }
    

    Other save example:

    if (savefile.ShowDialog() == DialogResult.OK)
    {
        pictureBit.Save(savefile.FileName,ImageFormat.Png);
    }