Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Use System.IO.StringReader :

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

Use the StringReader class, which inherits TextReader.


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();
}

You want a StringReader

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

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.