zoukankan      html  css  js  c++  java
  • c# 读写文件时文件正由另一进程使用

    c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件,在IO处理上遇到了无法操作的问题。

    文件“D:\log.txt”正由另一进程使用,因此该进程无法访问该文件。

    log.txt是一个日志文件,不定时都可能由另外的程序对它进行日志记录写入操作。

    今需要对日志文件读取出来,显示在日志查询里,需要用到了IO流。

    1、 FileStream fs = File.OpenRead(url);
    StreamReader sr = new StreamReader((System.IO.Stream)fs, System.Text.Encoding.Default);

    错误提示:文件“D:\Log\Cargoabc\logfilecargoabc.txt”正由另一进程使用,因此该进程无法访问该文件。

    2、StreamReader sr = File.OpenText(url);

    错误提示:错误提示:文件“D:\Log\Cargoabc\logfilecargoabc.txt”正由另一进程使用,因此该进程无法访问该文件。

    3、 FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);

    正确读取。

    总结:

    这样的情况,不单要与只读方式打开txt文件,而且,需要共享锁。还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作。

     

     

    ////////////////////////////////////////

     

    解决方案:

     

    FileStream _file = new FileStream(@”c:/a.txt”, FileMode.Create, FileAccess.ReadWrite);
    using (StreamWriter writer1 = new StreamWriter(_file))
    {
    writer.WriteLine(看你要写什么);
    writer1.Flush();
    writer1.Close();

     

    _file.Close();
    }

    ///////////////////////////////////

    File.Create  正由另一进程使用,因此该进程无法访问该文件。

         FileStream fs= File.Create(path);
                             fs.Close();
                            fs.Dispose();

     

  • 相关阅读:
    [转]fedora国内源常见配置
    [转]Fedora 添加国内源(sohu, 163)
    keepalived
    lvs详解
    ansible详解
    练习题:计算传入字符串中的【数字】、【字母】、【空格】和【其他】的个数
    面向对象(继承、重写、多态)以及异常处理
    面向对象详解以及封装案例解答
    进程、线程与GIL全局解释器锁详解
    python函数与模块(paramiko、socket模块、文件处理、装饰器、迭代器等)
  • 原文地址:https://www.cnblogs.com/furenjian/p/3010070.html
Copyright © 2011-2022 走看看