2pietjuh2
2pietjuh2

Reputation: 879

IOException was unhandled error

I have the following code, and I'm getting an IOException error. It says it is in use by a different process. I do not have the file opened somewhere, the application creates the file.

This is my code:

In function one:

System.IO.StreamWriter data = new System.IO.StreamWriter(@"c:\temp.txt");
data.WriteLine(temp);
data.Close()

after this, a second function is called which should process the temp file. The lines which do something with the IO are these:

string[] part = System.IO.File.ReadAllLines(@"c:\temp.txt");

in this function the string[] part is modified and added to a final complete file:

System.IO.File.AppendAllLines(Datas.Core.outputDir + @"\" + Datas.Core.outputName + ".txt", part);

I guess the System.IO.ReadAllLines function keeps the file busy, how can I change my code so I can access the file again?

Upvotes: 1

Views: 3875

Answers (3)

McGarnagle
McGarnagle

Reputation: 102793

You need to call data.Dispose() (not just Close) in order to completely release the file handle.

Upvotes: 1

Ben
Ben

Reputation: 3391

Put the System.IO.StreamWriter in a using statement so that it will get disposed properly:

using (System.IO.StreamWriter data = new System.IO.StreamWriter(@"c:\temp.txt"))
{
    data.WriteLine(temp);
}

This is how the example in MSDN is presented.

Upvotes: 0

Picrofo Software
Picrofo Software

Reputation: 5571

The method System.IO.File.ReadAllLines() will not keep the file busy, it will open the file for reading then close it again automatically upon finished. The problem might be in the following line

System.IO.File.AppendAllLines(Datas.Core.outputDir + @"\" + Datas.Core.outputName + ".txt", part);

I believe that it is better to use the class StreamWriter to append or write text to a specific file and control the writer (class) later.

Here's a sample code

string Path = @"C:\temp.txt"; // You can change this to anything you would like
StreamWriter _TextWriter = new StreamWriter(Path, true); // change to "false" if you do not want to append

Then you can use one of the following to:

! Append text to the last line

_TextWriter.Write("something");

! Create a new line at the end of the file then append text to the last line

_TextWriter.WriteLine("something");

Then close the StreamWriter using the following code when you finish processing the file

_TextWriter.Close();

Thanks,
I hope you find this helpful :)

Upvotes: 2

Related Questions