保存PDF文件失败,因为它正被另一个进程使用

时间:2016-05-26 22:11:58

标签: asp.net vb.net itextsharp

我正在尝试使用打开的文件对话框和使用功能的iTextSharp保存PDF:

Private Sub saveFileDialog(saveType As String)
    ' Displays a SaveFileDialog
    Dim saveFileDialog1 As New SaveFileDialog()
    Select Case saveType
        Case "PDF"
            saveFileDialog1.Filter = "PDF File|*.pdf"
            saveFileDialog1.Title = "Save a PDF File"
        Case "Image"
            saveFileDialog1.Filter = "PNG Image|*.png"
            saveFileDialog1.Title = "Save an Image File"
    End Select
    saveFileDialog1.ShowDialog()
    ' If the file name is not an empty string open it for saving.
    If saveFileDialog1.FileName <> "" Then
        ' Saves the Image via a FileStream created by the OpenFile method.
        Dim fs As System.IO.FileStream = CType(saveFileDialog1.OpenFile(), System.IO.FileStream)
        Select Case saveType
            Case "PDF"
                Dim doc As iTextSharp.text.Document = New iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, Bounds.Left, Bounds.Right, Bounds.Top, Bounds.Bottom)
                Dim wri As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, New FileStream(saveFileDialog1.FileName, FileMode.Create))
                doc.Open()
                Dim Image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Png)
                doc.Add(Image)
                doc.Close()
            Case "Image"
                bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png)
        End Select
        fs.Close()
    End If
End Sub

一切似乎都正常工作,直到我在文件保存对话框中点击保存,我收到错误:

"The process cannot access the file 'C:\Users\Daisy\Desktop\f.pdf' because it is being used by another process."

然后该文件保存到该位置但不可打开且为0字节。

我做错了什么以及如何解决?

1 个答案:

答案 0 :(得分:3)

您正在打开两个文件流到同一个文件。一旦用对话框打开文件,再次创建pdf writer的实例时。

Prepare for segue