C# 试图读取或写入受保护的内存。这通常表示其他内存已损坏

C# 试图读取或写入受保护的内存。这通常表示其他内存已损坏,c#,winforms,savefiledialog,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(如果我为文件提供了一个静态名称),则不会出现错误

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

如何解决问题。

这可能是问题所在:

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

请尝试以下代码

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

只是旁注(不是你问题的答案)。使用
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
代替
if(saveFileDialog1.FileName!=“”)
。另外,
Convert.ToString(Environment.SpecialFolder.MyDocuments)==“MyDocuments”
,不产生路径。您可以发布异常的堆栈跟踪吗?在哪一行出现错误?:)欢迎使用编码-您不断“添加”直到看到“麻烦点”-从“最小工作”开始,添加您的“真实项目”拥有的东西-但一个接一个-直到它不再工作。有工具可以帮助,但我不知道从内存,这是一个很长的时间。这可以让你得到错误的文件夹,但不是“试图读取或写入受保护的内存”,但我得到的错误之前,如果块。由于此代码无法进入if block.make if语句作为if(saveFileDialog1.ShowDialog()==DialogResult.OK)并重试“if(saveFileDialog1.ShowDialog()==DialogResult.OK)”这一行。我已编辑了整个答案。复制整个代码并重试。让我知道获取错误的行是否确定(saveFileDialog1.ShowDialog()==DialogResult.OK)是异常语句?