5St*_*yan 3 .net c# string file-io compare
我有一个将文本转储到文本文件的应用程序.我认为文本可能存在一个问题,即不包含正确的回车符,因此我正在编写一个测试,将该文件的内容与我在代码中声明的字符串变量进行比较.
例如:
1)代码创建一个包含文本的文本文件:
This is line 1
This is line 2
This is line 3
Run Code Online (Sandbox Code Playgroud)
2)我有以下字符串,我想比较它:
string testString = "This is line 1\nThis is line 2\nThis is line3"
Run Code Online (Sandbox Code Playgroud)
据我所知,我可以打开文件流阅读器并逐行读取文本文件并将其存储在可变字符串变量中,同时在每行后附加"\n",但想知道这是否重新发明了轮子(换句话说, .NET有一个类似于此的内置类).提前致谢.
你可以使用StreamReader的ReadToEnd()方法来读取单个字符串中的内容
using System.IO;
using(StreamReader streamReader = new StreamReader(filePath))
{
string text = streamReader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
注意:您必须确保释放资源(上面的代码使用"using"来执行此操作)并且ReadToEnd()方法假定流知道它何时到达结束.对于服务器仅在您请求数据时发送数据并且不关闭连接的交互式协议,ReadToEnd可能会无限期地阻塞,因为它没有达到目的,应该避免,并且您应该注意字符串中的当前位置应该在一开始.
您也可以使用ReadAllText
// Open the file to read from.
string readText = File.ReadAllText(path);
Run Code Online (Sandbox Code Playgroud)
这很简单,它打开一个文件,读取所有行,并负责关闭.