Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileStream: used by another process error

I have two different modules that need access to a single file (One will have ReadWrite Access - Other only Read). The file is opened using the following code in one of the modules:

FileStream fs1 = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.Read);

Th problem is that the second module fails while trying to open the same file using the following code:

FileStream fs = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.Read);

Do I need to set some additional security parameters here?

like image 302
A9S6 Avatar asked Mar 05 '10 13:03

A9S6


People also ask

How do I overwrite a FileStream in C#?

Just use FileMode. Open or FileMode. Truncate to overwrite the file: namespace System.IO { // // Summary: // Specifies how the operating system should open a file.

How do you fix the process Cannot access the file because it is being used by another process in C #?

This can happen if the file referenced is open in another program or if a crash occurs while uploading. To resolve it, first make sure that no users have the file open anywhere, then reboot the machine to make sure it is not open as a remnant from a crash.

What is the use of FileStream in C#?

The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.

What is stream and FileStream?

Stream is a representation of bytes. Both these classes derive from the Stream class which is abstract by definition. As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.


2 Answers

On the FileStream that only READS the file, you need to set it as

FileShare.ReadWrite

FileStream fs = new FileStream(@"D:\post.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

other wise the original FileStream would not be able to write back to it...its just a volley back and forth between the two streams, make sure you hand back what the other needs

like image 145
curtisk Avatar answered Oct 21 '22 22:10

curtisk


When opening the second FileStream, you also need to specify FileShare.Read, otherwise it will try to open it with exclusive access, and will fail because the file is already open

like image 28
Thomas Levesque Avatar answered Oct 21 '22 22:10

Thomas Levesque