0

我正在开发一个 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();
        }
     }

我该如何解决这个问题。

4

2 回答 2

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();
    }
于 2013-04-18T11:38:06.567 回答
0

这可能是问题所在:

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

于 2013-04-18T11:20:29.590 回答