C#:将图像保存到文档文件夹时出错

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

我的 C# 窗体上显示了一张图片。当用户单击 "Save Image" 按钮时,它会弹出一个 Visual Basic 输入框。我正在尝试向我的表单添加功能,允许用户在通过 Visual Basic 输入框输入图像名称时保存图像。

首先,我添加了这段代码,

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");
    } 

但是,当我 运行 程序并单击保存按钮时,它给出了这个异常:"An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll"

然后我对代码添加了一些更改,使其看起来像这样,

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);                                
    }

当我 运行 这段代码时,它不再给出异常,但它会将图像保存在我的 c#->bin->debug 文件夹中。我知道这可能不是理想的方式,但我如何设置它的路径以便将图像保存在文档文件夹中。

您没有设置路径,有关详细信息,请参阅 MSDN

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

显示对话框的其他工作示例:

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();
}

其他保存示例:

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