[英]Usage of StreamReader in C#
I want to read a file data.json and convert it to a string. 我想读取一个文件data.json并将其转换为字符串。
My code is this one: 我的代码是这样的:
String json = null;
using (StreamReader sr = new StreamReader("data.json"))
{
json = sr.ReadToEnd();
}
but Visual Studio tells me that StreamReader
does not expect a String as constructor argument. 但是Visual Studio告诉我StreamReader
不希望将String作为构造函数参数。
How can I tell StreamReader that I want to read the file data.json? 如何告诉StreamReader我想读取文件data.json?
Actually StreamReader
supports constructor which accepts file path for most platforms, but not all. 实际上, StreamReader
支持构造函数,该构造函数接受大多数平台(但不是全部)的文件路径 。 But anyway - simply use File.ReadAllText
: 但是无论如何-只需使用File.ReadAllText
:
string json = File.ReadAllText("data.json");
It creates StreamReader
internally ( link to source ): 它在内部创建StreamReader
( 链接到source ):
using (var sr = new StreamReader(path, encoding))
return sr.ReadToEnd();
UPDATE: You can always pass stream to StreamReader
. 更新:您始终可以将流传递给StreamReader
。 Use FileStream
to open stream for reading file, and then pass it to StreamReader
: 使用FileStream
打开用于读取文件的流,然后将其传递给StreamReader
:
string json = null;
using (var stream = new FileStream("data.json", FileMode.Open))
using (var reader = new StreamReader(stream))
json = reader.ReadToEnd();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.