读文件时文件正由另一进程使用,因此该进程无法访问该文件

场景:cs系统下产生的日志文件在登陆后需要在系统中读取例如错误日志并显示到系统中。

 

错误方式:

        /// <summary>
        /// 根据导航地址加载内容
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        protected override object LoadContent(Uri uri)
        {
            var sb = new StringBuilder();
            var logPath = string.Format(@"{0}\{1}", _root, uri.ToString());

            using (var fileStream = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true))
            {
                using (var streamReader = new StreamReader(fileStream, System.Text.Encoding.Default))
                {
                    while (streamReader.EndOfStream == false)
                    {
                        sb.AppendLine(streamReader.ReadLine());
                    }
                }
                return sb.ToString();
            }
        }

错误原因:只读方式打开文件,因为其他文件可能正在往里写数据,所以要开启共享锁,如 FileShare.ReadWrite

正确:

        /// <summary>
        /// 根据导航地址加载内容
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        protected override object LoadContent(Uri uri)
        {
            var sb = new StringBuilder();
            var logPath = string.Format(@"{0}\{1}", _root, uri.ToString());
            
            using (var fileStream = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 4096, useAsync: true))
            {
                using (var streamReader = new StreamReader(fileStream, System.Text.Encoding.Default))
                {
                    while (streamReader.EndOfStream==false)
                    {
                        sb.AppendLine(streamReader.ReadLine());
                    }
                }
                return sb.ToString();
            }
        }

 

posted @ 2019-07-04 19:21  江宁织造  阅读(2033)  评论(0编辑  收藏  举报