您当前的位置:首页 > 文章 > C# 错误:“System.IO.IOException: 文件“xxx”正由另一进程使用,因此该进程”解决方法

C# 错误:“System.IO.IOException: 文件“xxx”正由另一进程使用,因此该进程”解决方法

作者:猿长大人 时间:2024-07-12 阅读数:385 人阅读
问题描述
A程序不断的将日志信息追加到日志文件的末尾,B程序不断的从日志文件中读取最后一行(使用File.ReadLines(string path)方法)。
在B程序读取的同时A程序执行写入,报出如下错误信息:

System.IO.IOException: 文件“xxx”正由另一进程使用,因此该进程无法访问此文件。

解决方法
因为需要按行读取数据,所以采用File.ReadLines(string path)方法,但该方法在读取时会锁住文件不让A程序继续写入。若不想禁止对文件的写入,应使用如下参数创建文件流:
new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
如此以来,改写一个ReadLines方法就好:
public static IEnumerable<string> ReadLines(string path,Encoding encode = null)
{
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan))
    using (var sr = new StreamReader(fs, encode ?? Encoding.UTF8))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            yield return line;
        }
    }
}
                        
原文链接:https://blog.csdn.net/lgj123xj/article/details/124402973

本站大部分文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了您的权益请来信告知我们删除。邮箱:1451803763@qq.com