簡體   English   中英

該進程無法訪問文件'D:.txt',因為它正在由c#中的另一個進程使用

[英]The process cannot access the file 'D:.txt' because it is being used by another process in c#

我有一個pdf文件,我正在嘗試使用itext在c#中讀取和寫入文本文件。現在我已經創建了一個文本文件並嘗試將我的pdf值寫入其中,但是它給出了以下錯誤。

該進程無法訪問文件'D:\\ 9008028901.txt',因為該文件正在被另一個進程使用。

這是我在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將創建它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM