2013-04-18 62 views
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(); 
     } 
    } 

我怎樣才能解決這個問題。

+3

只是一個側面說明(不是回答你的問題)。使用'if(saveFileDialog1.ShowDialog()== DialogResult.OK)'而不是'if(saveFileDialog1.FileName!=「」)''。 –

+0

此外,'Convert.ToString(Environment.SpecialFolder.MyDocuments)==「MyDocuments」',不會產生路徑。 –

+1

你能從異常中發佈堆棧跟蹤嗎? –

回答

0

這可能是問題:

不能使用Convert.ToString(Environment.SpecialFolder.MyDocuments)得到的文件夾路徑作爲一個字符串,它只是一個枚舉。您需要使用Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)來獲取路徑作爲枚舉值的字符串。

+0

嘗試過,仍然出現問題。 –

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

但我得到錯誤之前,如果塊。因爲這個代碼不能進入if塊。 –

+0

使if語句成爲if(saveFileDialog1.ShowDialog()== DialogResult。確定),然後再試一次 –

+0

是的,但仍然是同樣的問題。 –

相關問題