- 第一种:
txt有多少行就会返回长度为多少的List<string>
/// <summary>
/// 读取txt文件内容
/// </summary>
/// <param name="Path">文件地址</param>
public static List<string> ReadTxtContent(string txtPath)
{
string Path = txtPath;
StreamReader sr = new StreamReader(Path, Encoding.Default);
string content;
List<string> vs = new List<string>();
while ((content = sr.ReadLine()) != null)
{
vs.Add(content);
}
sr.Close();
return vs;
}
- 第二种:
返回txt的全部字符串
/// <summary>
/// 读取txt文件内容
/// </summary>
/// <param name="Path">文件地址</param>
public static string ReadTxtContent(string txtPath)
{
string Path = txtPath;
StreamReader sr = new StreamReader(Path, Encoding.Default);
string content;
string res="";
while ((content = sr.ReadLine()) != null)
{
res+=content+"\n";
}
sr.Close();
return res;
}
本文介绍了两种读取TXT文件的方法:第一种方法将文件内容按行读取并存储为字符串列表;第二种方法则读取整个文件内容为单一字符串。这两种方法均使用StreamReader并指定默认编码。
5787

被折叠的 条评论
为什么被折叠?



