In C#, how can I create a TextReader object from a string (without writing to disk)

你离开我真会死。 提交于 2019-11-30 05:33:10

Use System.IO.StringReader :

using(TextReader sr = new StringReader(yourstring))
{
    DoSomethingWithATextReader(sr);
}
Ilia G

Use the StringReader class, which inherits TextReader.

You want a StringReader

var val = "test string";
var textReader = new StringReader(val);

StringReader is a TextReader (StreamReader is too, but for reading from streams). So taking your first example and just using it to construct the CsvReader rather than trying to construct a StreamReader from it first gives:

TextReader sr = new StringReader(TextBox_StartData.Text);
using(CsvReader csv = new CsvReader(sr, true))
{
  DetailsView1.DataSource = csv;
  DetailsView1.DataBind();
}

Simply use the StringReader class. It inherits from TextReader.

If you look at the documentation for TextReader, you will see two inheriting classes. And one of them is StringReader, which seems to do exactly what you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!