我有一个 pdf 文件,我正在尝试使用 itext 在 c# 中读取和写入文本文件。现在我创建了一个文本文件并尝试将我的 pdf 值写入其中,但它给出了以下错误..
The process cannot access the file 'D:\9008028901.txt' because it is being used by another process.
这是我在 C# 中的代码..
public bool ExtractText(string inFileName, string outFileName)
{
StreamWriter outFile = null;
try
{
// Create a reader for the given PDF file
PdfReader reader = new PdfReader(inFileName);
outFile = File.CreateText(outFileName);
outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);
在我的代码中,正在创建文本文件,但我无法在其中写入任何内容。我的文本文件是空白的。 请帮助我..
最佳答案
File.CreateText
方法返回一个保持文件打开状态的 StreamWriter
对象。这未关闭,然后您尝试使用 new StreamWriter
调用再次打开该文件,因此遇到文件正在使用错误。要解决此问题,您需要关闭第一个 StreamWriter
outFile = File.CreateText(outFileName);
outFile.Close();
outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);
总的来说,这似乎有点浪费。只创建一次 StreamWriter
实例会更有效率
outFile = new StreamWriter(outFile, false, System.Text.Encoding.UTF8);
File.CreateText
方法在这里似乎是不必要的。如果文件不存在 StreamWriter
将创建它
关于c# - 该进程无法访问文件 'D:.txt',因为它正在被 c# 中的另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21846752/