Create 2 FileStream on the same file in the same process

Serge Weinstock picture Serge Weinstock · Nov 21, 2011 · Viewed 8.4k times · Source

I'm trying to create a temporary file that will be automatically deleted.

stream = new FileStream(
           tmpFilePath, 
           FileMode.OpenOrCreate, 
           FileAccess.ReadWrite, 
           FileShare.ReadWrite, 
           4096, 
           FileOptions.DeleteOnClose|FileOptions.RandomAccess
           );

This file will be used by a 3rd party API which will also create a FileStream:

stream = new FileStream(
          tmpFilePath, 
          FileMode.Open, 
          FileAccess.Read, 
          FileShare.Read);

I think I've tried all possible combination of flags but I always get a "The process cannot access the file 'XXX' because it is being used by another process..."

Am I doing something wrong? Is there a way around?

Answer

Steve Wellens picture Steve Wellens · Nov 21, 2011

According to the documentation, yes.

http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

Excerpt:

Read: Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.