Search code examples
c#fileioreadonly

Binary Reader with Filemode.Open Blocks file for other programs


I am trying to make a tagging solution for .wav audiofiles.

For that reason I need to open the file to read out it's Tags. The code for that starts out like this:

this.Reader = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read));
this.RiffId = Encoding.ASCII.GetString(Reader.ReadBytes(4)); // excluding 8 bit header
this.FileSize = Reader.ReadInt32(); // size of entire file (4 bytes)
this.FileType = Encoding.ASCII.GetString(Reader.ReadBytes(4));

From my understanding, this will open the File readonly normally? However, when I open the audio file while it is open in my application, media players spit out an error stating that the file is beeing blocked by my program: enter image description here

I whish to have the file readonly, writing will always be a full Copy of the file.

Having the possibility to read the file in two programs at a time is necessary when listening to the audio in order to tag the file. Closing the file while listening to it is not so easily possible as I want to keep my application responsive. Additional data from the riff chunks is loaded and stored in buffer when nessesary only.


Solution

  • this.Reader = new BinaryReader(File.Open(path,FileMode.Open,FileAccess.Read,FileShare.Read));
    

    FileMode.Open specifies, how to proceed with the file. More on that on https://learn.microsoft.com/en-us/dotnet/api/system.io.filemode?view=net-5.0

    some examples: Open 3
    Specifies that the operating system should open an existing file. The ability to open the file is dependent on the value specified by the FileAccess enumeration. A FileNotFoundException exception is thrown if the file does not exist.

    Append 6
    Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.

    Truncate 5
    Specifies that the operating system should open an existing file. When the file is opened, it should be truncated so that its size is zero bytes. This requires Write permission. Attempts to read from a file opened with FileMode.Truncate cause an ArgumentException exception.

    FileAccess specifies your own file access https://learn.microsoft.com/en-us/dotnet/api/system.io.fileaccess?view=net-5.0

    FileShare specifies the access other threads have to the file https://learn.microsoft.com/en-us/dotnet/api/system.io.fileshare?view=net-5.0