尝试读取或写入受保护的内存。这通常表明其他内存已损坏

时间:2013-04-18 11:13:09

标签: c# winforms savefiledialog

我正在开发一个Windows窗体项目,它会创建一个PDF文件。我想保存用户想要的文件。我为此使用了SaveFileDialog。当我单击表单上的“另存为PDF”按钮时,我会收到此错误代码。

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

如果我不使用SaveFileDialog(如果我为文件指定静态名称),请不要收到错误。

这是按钮点击代码:

    private void button2_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
        saveFileDialog1.Filter = "(*.pdf)|*.pdf|All Files (*.*)|*.*";
        saveFileDialog1.FilterIndex = 1;
        saveFileDialog1.ShowDialog();


        if (saveFileDialog1.FileName != "")
        {
            iTextSharp.text.Document pdfDosya = new iTextSharp.text.Document(PageSize.A4, 20, 20, 10, 10);
            PdfWriter.GetInstance(pdfDosya, new FileStream(saveFileDialog1.FileName, FileMode.Create));//TODO dosya ismi
            pdfDosya.Open();
        }
     }

如何解决问题。

2 个答案:

答案 0 :(得分:0)

这可能是问题所在:

您不能使用Convert.ToString(Environment.SpecialFolder.MyDocuments)将文件夹路径作为字符串获取,它只是一个枚举。您需要使用Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)将路径作为枚举值的字符串。

答案 1 :(得分:0)

试试此代码

    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory =   Convert.ToString(Environment.SpecialFolder.MyDocuments);
    saveFileDialog1.Filter = "(*.pdf)|*.pdf|All Files (*.*)|*.*";
    saveFileDialog1.FilterIndex = 1;

   if(saveFileDialog1.ShowDialog() == DialogResult.OK) 
   {
        MemoryStream ms = new MemoryStream();
        iTextSharp.text.Document document = new Document(PageSize.A4, 10.0F, 10.0F,100.0F,0.0F);
        document.AddTitle("FileName.pdf");
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        document.Open();
    }