zoukankan      html  css  js  c++  java
  • c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件

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

    1、 

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

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

    2、

    StreamReader sr = File.OpenText(url);

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

    3、

    string textInfo = File.ReadAllText(filePath,Encoding.Default);

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

    4、正确读取方式

    FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    
    StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
    
    StringBuilder sb = new StringBuilder();
    while (!sr.EndOfStream)
    {
    sb.AppendLine(sr.ReadLine()+"<br>");
    }

     

    总结:

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

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

  • 相关阅读:
    遥远的国度(D12 树链剖分)
    Codechef DGCD Dynamic GCD(D12 树上GCD)
    html总结
    数据库大总结
    html笔记
    Linux常用快捷键
    进程
    多进程
    进程介绍
    网络并发
  • 原文地址:https://www.cnblogs.com/code1992/p/11533212.html
Copyright © 2011-2022 走看看