• C# 只读模式读取txt文件内容


    读取txt文件时,提示异常:

    文件“..Logall_info.txt”正由另一进程使用,因此该进程无法访问此文件

    原因:

    日志文件通过lognet生成的日志文件(C#使用log4net记录日志),自动任务一直在进行,文件流没有关闭。

    所以获取文件内容时,会提示进程被占用。

    尝试方案:

    通过System.IO.File读取 -- ReadAllLines/ReadAllText等方法,报错进程占用异常

    var fileContent = File.ReadAllText(_filename);

    通过FileStream读取数据

    1     using (FileStream fsRead = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    2     {
    3         int fsLen = (int)fsRead.Length;
    4         byte[] heByte = new byte[fsLen];
    5         fsRead.Read(heByte, 0, heByte.Length);
    6         string myStr = System.Text.Encoding.UTF8.GetString(heByte);
    7     }

    测试:OK

    重点在FileShare这个参数,FileShare.ReadWrite 允许打开文件后,依然可以进行读取。

    也使用StringBuilder读取行数据,通过FileStream和StreamReader处理数据流:

     1 public static string ReadTextFromFileWithReadOnlyMode(string filename)
     2 {
     3     string content;
     4     using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     5     {
     6         using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default))
     7         {
     8             StringBuilder sb = new StringBuilder();
     9             while (!sr.EndOfStream)
    10             {
    11                 sb.AppendLine(sr.ReadLine() + "<br>");
    12             }
    13             content = sb.ToString();
    14         }
    15     }
    16     return content;
    17 }
  • 相关阅读:
    149. Max Points on a Line(js)
    148. Sort List(js)
    147. Insertion Sort List(js)
    146. LRU Cache(js)
    145. Binary Tree Postorder Traversal(js)
    144. Binary Tree Preorder Traversal(js)
    143. Reorder List(js)
    142. Linked List Cycle II(js)
    141. Linked List Cycle(js)
    140. Word Break II(js)
  • 原文地址:https://www.cnblogs.com/kybs0/p/12018393.html
Copyright © 2020-2023  润新知