当前位置:首页 > 码农资料 > 正文内容

C#读取文本文件

CCSSRW3年前 (2021-05-06)码农资料1880

添加命名空间

using System.IO;

读取全部文本行

string path="c:\\test.txt";
if (File.Exists(path))
{
    string ReadText = File.ReadAllText(path);
}

但是这种读取方法如遇到文件被锁定时会报错。为避免这个问题,使用FileStream就可以解决

if (File.Exists(path))
{
    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    byte[] bytes = new byte[fs.Length];
    fs.Read(bytes, 0, bytes.Length);
    fs.Close();
    fs.Dispose();
    string ReadText= new string(Encoding.UTF8.GetChars(bytes));
}


扫描二维码推送至手机访问

本文链接:http://xinrui.ren/post/67.html