Search code examples
c#exceptionfilestreamaac

Error "file in use" when playing aac while appending bytes to aac


var outputfile = "outputfile.aac";     
var fileList = new List<string>
                {
                    "1.aac",
                    "2.aac",
                    "3.aac",
                    "4.aac",
                    "5.aac",
                    "6.aac"
                };

                foreach (var file in fileList)
                {
                    using (var stream = new FileStream(outputfile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                    {
                        var bytes = File.ReadAllBytes(file);
                        stream.Write(bytes, 0, bytes.Length);
                        stream.Flush();
                    }
                }

I try to join aac files in fileList into outputfile. when writing file "3.aac" to outputfile.aac, I open outputfile with MediaPlayer, then the FileStream returns exception "file in use", even FileShare mode is ReadWrite, it means that other processes can read and write to the file. So where is the reason?

However, in this case output file is not blocked

Stream s = resp.GetResponseStream();
                    var fs = File.Exists(outputFile) ? new FileStream(outputFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
                        : new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                    byte[] buffer = new byte[4096];
                    while (s.CanRead)
                    {
                        int bytesRead = s.Read(buffer, 0, buffer.Length);
                        fs.Write(buffer, 0, bytesRead);
                    }

P/s: I found that the reason because it's aac file


Solution

  • When you use FileShare.ReadWrite you allow subsequent opening of the file in read or write mode.

    MediaPlayer then opens the file with FileShare.Read on its side, denying you write access to the file.