I am trying to stream video file . when i open the same video file in another tab of browser , i get the message "file is being used by another process" . if I use FileShare.ReadWrite in file.open method then error goes away but video doesn't play in browser . can someone pl. help .

public HttpResponseMessage Get([string id)
        {
            var path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["path"] + "/" + id);
            var video = new VideoStream(path);
            HttpResponseMessage response = Request.CreateResponse();
            var contentType = ConfigurationManager.AppSettings[Path.GetExtension(id)];
            response.Content = new PushStreamContent(video.WriteToStream,  new MediaTypeHeaderValue(contentType));

            return response;
        }


        public class VideoStream
        {
            private readonly string _filename;

            public VideoStream(string filename)
            {
                _filename = filename;
            }


            public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
            {
                try
                {
                    var buffer = new byte[65536];

                    using (var video = File.Open(_filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        var length = (int) video.Length;
                        var bytesRead = 1;

                        while (length > 0 && bytesRead > 0)
                        {
                            bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                             await outputStream.WriteAsync(buffer, 0, bytesRead);

                            length -= bytesRead;
                            video.Flush();

                        }
                    }
                }
                catch (HttpException ex)
                {
                    return;
                }
                finally
                {


                 //   outputStream.Close();
                  //  outputStream.Flush();
                }
            }



        }
1

There are 1 best solutions below

7
On

You should use: File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read);

Assuming the file lock comes from the server. Is that the case, or is it a client side thing?