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

Hairgami_Master picture Hairgami_Master · Oct 20, 2011 · Viewed 86.5k times · Source

I'm using A Fast CSV Reader to parse some pasted text into a webpage. The Fast CSV reader requires a TextReader object, and all I have is a string. What's the best way to convert a string into a TextReader object on the fly?

Thanks!

Update- Sample code- In the original sample, a new StreamReader is looking for a file called "data.csv". I'm hoping to supply it via TextBox_StartData.Text.

Using this code below doesn't compile.

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

The new StreamReader(sr) tells me it has some invalid arguments. Any ideas?

As an alternate approach, I've tried this:

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

but I get an Illegal characters in path Error. Here's a sample of the string from TextBox_StartData.Text:

Fname\tLname\tEmail\nClaude\tCuriel\[email protected]\nAntoinette\tCalixte\[email protected]\nCathey\tPeden\[email protected]\n

Any ideas if this the right approach? Thanks again for your help!

Answer

Steve B picture Steve B · Oct 20, 2011

Use System.IO.StringReader :

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