0

我正在尝试流式传输视频文件。当我在浏览器的另一个选项卡中打开相同的视频文件时,我收到消息“文件正在被另一个进程使用”。如果我在 file.open 方法中使用 FileShare.ReadWrite,则错误消失但视频无法在浏览器中播放。有人可以吗?帮助 。

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();
                }
            }



        }
4

1 回答 1

2

您应该使用: File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read);

假设文件锁来自服务器。是这样,还是客户端的事情?

于 2014-05-01T23:23:44.443 回答