Search code examples
c#streamfilestreamstreamwritermediaelement

Can't Use Stream.Write method while playing same file in MediaElement


So lets say I have a file which has around 2MB already downloaded and written which is being played using a MediaElement. So while the media is being played, I want to download and write the rest of the file. If I use this method, I get an IOExecption error indicating the file is already in use.

 using (Stream WriteStream = new FileStream(filename, FileMode.OpenOrCreate))
      {
        WriteStream.Seek(seekpos, SeekOrigin.Begin);
        WriteStream.Write(buffer, 0, buffer.Length);
        WriteStream.Close();
      }

But if I use this method, it works fine.

FileStream1 = new System.IO.FileStream(filename, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
FileStream1.Write(buffer, 0, buffer.Length);

So I could use the second method, but I want to be able to seek and write at certain positions which I can't do using the second method. So is there anyway in which I can use the first method. Does it have something to do with the FILEMODE or FILEACCESS? Thanks :)


Solution

  • Never-mind I figured it out. I can use this to seek and write at any position. Stupid of me to not realise this.

    FileStream1 = new System.IO.FileStream(filename, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
    FileStream1.Seek(seekpos,SeekOrigin.Begin);
    FileStream1.Write(buffer, 0, buffer.Length);