-1

I have 2 Filestreams like this:

using (var fs = new FileStream(source, FileMode.Open, FileAccess.Write, FileShare.Read)){
//some code here
var checksum = getChecksum(source);

}

public long getChecksum(string source){
    using (var fs = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)){
    //Error: The process cannot access the file 'C:\Temp\archive.dat' because it is being used by another process.
    }
}


why does this error appear? I already set the FileAccess to Read / ReadWrite / ... but nothing worked. And I can't pass the Stream to the getChecksum() function, because I use the function in other places.

shouldn't the above stream allow for reading?

Create 2 FileStream on the same file in the same process I couldn't find my awnser in this thread.

  • It is a windows error because FileStream is really a wrapper for a Window DLL. You can change the property of the file in windows to be shared which may solve issue. – jdweng Mar 12 '23 at 02:53

1 Answers1

0

You are trying to open a second FileStream while the first is still open as the using block is still in scope. The docs say that when using FileShare.Read additional permissions may be required.

In the other thread you linked someone mentioned may need to set the FileShare mode on the second stream to FileShare.ReadWrite so the first still has access. This is probably the most likely cause as the second is trying to obtain exclusive access except for reads, but there is already a write stream open.

Also you could try calling Flush() on the first FileStream to force the data to be written before calling getCheckSum().

using (var fs = new FileStream(source, FileMode.Open, FileAccess.Write, FileShare.Read)){
//some code here

//Force the buffered data to be written
fs.Flush()
var checksum = getChecksum(source);

}

public long getChecksum(string source){
    using (var fs = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){ //FileShare.ReadWrite so first FileStream can still access
    }
}
Damien D
  • 46
  • 4