【问题标题】:C# read line from stringC#从字符串中读取行
【发布时间】:2018-11-26 03:51:51
【问题描述】:

如何从字符串中读取所有行。

我测试过的代码(不工作)

string line;
line = mycontent;
StreamReader streamReader = new StreamReader(line);
string data = streamReader.ReadToEnd();
MessageBox.Show(data);

此代码显示错误。 我想创建一个简单的程序,它可以从字符串而不是文件路径中读取到结束。我了解到 StreamReader 可用于从文件路径读取文件。

我的意图是我有一个string mycontent = "Simple",我想把这个mycontent 读到最后。但是mycontent 每次我按下按钮都会改变。 So I want to create something that similar to this code.

谢谢。

PS。错误说'Illegal characters in path.'

【问题讨论】:

  • 你想要一个 StringReader,而不是 StreamReader

标签: c#


【解决方案1】:

StreamReader constructor 将路径作为参数,而不是文字字符串。

请改用StringReader。而要逐行阅读,请使用ReadLine() 方法。

【讨论】:

  • @Fair:我认为这发生在我们所有人身上。我有点不喜欢 C# API。他们应该使用FileInfo 参数而不是字符串。这样会更清楚。
【解决方案2】:

使用StringReader()逐行读取字符串:

StringReader reader = new StringReader(multilinestring);
while ((line = reader.ReadLine()) != null)
{
    //do what you want to do with the line;
};

【讨论】: