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

StackOverflow https://stackoverflow.com/questions/21846752

Question

I have a pdf file which i am trying to read and write into text file in c# using itext.Now i have created a text file and trying to write my pdf values into it but it is giving following error..

The process cannot access the file 'D:\9008028901.txt' because it is being used by another process.

Here is my code in 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);

Here in my code text file is getting created but i ma not able to write any thing in it.My text file is blank. Please help me..

Était-ce utile?

La solution

The File.CreateText method returns a StreamWriter object that is holding the file open. This is not closed and then you try to open the file again with the new StreamWriter call and hence run into the file in use error. To fix this you need to close the first StreamWriter

outFile = File.CreateText(outFileName);
outFile.Close();
outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);

Overall this seems a bit wasteful. It would be much more efficient to just create the StreamWriter instance one time

outFile = new StreamWriter(outFile, false, System.Text.Encoding.UTF8);

The File.CreateText method is seemingly unnecessary here. If the file doesn't exist StreamWriter will create it

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top