views:

55

answers:

2

Hello,

How do I read and write on a text file without getting the exception that "File is already in use by another app"??

I tried File.readalltext() and File.Appendalltext() functions..I'm just starting out with filestream.

Which would work out best in my scenario? I would appreciate some code snipplets too ..

Thanks

A: 

You need to make sure the file is not being used by any other application.

With your own application, you cannot read from a file multiple times without closing the stream between reads.

You need to find out why the file is in use - a tool like FileMon can help finding out.

Oded
+2  A: 

This is all to do with the lock and sharing semantics that you request when opening the file.

Instead of using the shortcut approach of File.ReadAllText(), try looking into using a System.IO.FileStream and a System.IO.StreamReader / System.IO.StreamWriter.

To open a file:

using (var fileStream = new FileStream(@"c:\myFile", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var streamReader = new StreamReader(fileStream))
{
  var someText = streamReader.ReadToEnd();
}

Note the FileShare.ReadWrite - this is telling the stream to allow sharing to either other readers or other writers.

For writing try something like

using (var fileStream = new FileStream(@"c:\myFile", FileMode.Create, FileAccess.Write, FileShare.Read))
using (var streamWriter = new StreamWriter(fileStream))
{
  streamWriter.WriteLine("some text");
}

Note the FileShare.Read - this is telling the stream to allow sharing to readers only.

Have a read around the System.IO.FileStream and its constructor overloads and you can tailor exactly how it behaves to suit your purpose.

Rob Levine
Your second code block says `FileShare.Read`, not `FileShare.Write`
Matt Ellen
@Matt Ellen. Corrected - thanks.
Rob Levine