首页 > 解决方案 > System.IO.IOException 使用 itext 写入 PDF 文件

问题描述

我正在使用 iText v5.5.5、Visual Studio 2013、.NET Framework 4.5、Windows 7 x64

我检查了这个问题System.IO.IOException: 'The process cannot access the file '@.txt' because it is being used by another process.' 在许多其他人中,试图找到持久性System.IO.IOException 的可能解决方案:进程无法访问文件 VDP.Temp.1.pdf

到目前为止,我尝试了这个,但仍然在以下位置出现 IO 错误:

"File.Delete(generatedFilePath)"

任何可能的解决方案?

private static string GetTemporaryFilePath()
{
    var appDirectoryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    var generatedFilePath = Path.Combine(appDirectoryPath, "VDP.Temp.1.pdf");
    
    if (File.Exists(generatedFilePath))               
    {
        FileStream Stream3 = null;
        try
        {
            Stream3 = File.Open(generatedFilePath, FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (IOException Er)
        {
            string message = Er.Message;
            string title = "";
            MessageBoxButtons buttons = MessageBoxButtons.OK;
            MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);
        }
        finally
        {
            Stream3.Close();
            Stream3.Dispose();
            File.Delete(generatedFilePath);
        }
    }
    
    return generatedFilePath;
}

另一个谜题中同样的错误也持续存在于:

document.Close();
        private string GeneratePreviewPdfFileFromBlank()
        {            
            // compute temporary file location
            var generatedFilePath = GetTemporaryFilePath();

       try
            {
                // then generate the temporary file
                var pageSize = new iTextSharp.text.Rectangle(0, 0, SourcePdfPageSize.Width, SourcePdfPageSize.Height);

                var document = new Document(pageSize);
                var stream = File.OpenWrite(generatedFilePath);
                var writer = PdfWriter.GetInstance(document, stream);

                document.Open();

                document.SetMargins(0, 0, 0, 0);
                document.SetPageSize(pageSize);

                document.NewPage();

                WriteLine(writer, pageSize, File0, _lines0, PreviewLineIndex);
                WriteLine(writer, pageSize, File1, _lines1, PreviewLineIndex);
                WriteLine(writer, pageSize, File2, _lines2, PreviewLineIndex);
                WriteLine(writer, pageSize, File3, _lines3, PreviewLineIndex);
                WriteLine(writer, pageSize, File4, _lines4, PreviewLineIndex);

                stream.Flush(true);

                document.Close();
                writer.Dispose();
                stream.Dispose();
                document.Dispose();
            }
            catch (Exception Er)
            {

            }

            return generatedFilePath;
        }

标签: c#itextioexception

解决方案


推荐阅读