[英]In C#, how can I create a TextReader object from a string (without writing to disk)
I'm using A Fast CSV Reader to parse some pasted text into a webpage. 我正在使用快速CSV阅读器将一些粘贴的文本解析为网页。 The Fast CSV reader requires a TextReader object, and all I have is a string.
Fast CSV阅读器需要一个TextReader对象,而我所拥有的只是一个字符串。 What's the best way to convert a string into a TextReader object on the fly?
在运行中将字符串转换为TextReader对象的最佳方法是什么?
Thanks! 谢谢!
Update- Sample code- In the original sample, a new StreamReader is looking for a file called "data.csv". 更新 - 示例代码 - 在原始示例中,新的StreamReader正在查找名为“data.csv”的文件。 I'm hoping to supply it via TextBox_StartData.Text.
我希望通过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. new StreamReader(sr)
告诉我它有一些无效的参数。 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.
但我
Illegal characters in path Error.
得到一个Illegal characters in path Error.
Here's a sample of the string from TextBox_StartData.Text: 这是TextBox_StartData.Text中字符串的示例:
Fname\tLname\tEmail\nClaude\tCuriel\tClaude.Curiel@email.com\nAntoinette\tCalixte\tAntoinette.Calixte@email.com\nCathey\tPeden\tCathey.Peden@email.com\n
Any ideas if this the right approach? 如果这是正确的方法,任何想法? Thanks again for your help!
再次感谢你的帮助!
Use System.IO.StringReader : 使用System.IO.StringReader :
using(TextReader sr = new StringReader(yourstring))
{
DoSomethingWithATextReader(sr);
}
使用继承TextReader
的StringReader
类。
You want a StringReader 你想要一个StringReader
var val = "test string";
var textReader = new StringReader(val);
StringReader
is a TextReader
( StreamReader
is too, but for reading from streams). StringReader
是一个TextReader
( StreamReader
也是,但是用于从流中读取)。 So taking your first example and just using it to construct the CsvReader
rather than trying to construct a StreamReader
from it first gives: 所以拿你的第一个例子,然后用它来构造
CsvReader
而不是试图从它构造StreamReader
首先给出:
TextReader sr = new StringReader(TextBox_StartData.Text);
using(CsvReader csv = new CsvReader(sr, true))
{
DetailsView1.DataSource = csv;
DetailsView1.DataBind();
}
Simply use the StringReader class. 只需使用StringReader类。 It inherits from TextReader.
它继承自TextReader。
If you look at the documentation for TextReader
, you will see two inheriting classes. 如果查看
TextReader
的文档 ,您将看到两个继承类。 And one of them is StringReader
, which seems to do exactly what you want. 其中一个是
StringReader
,它似乎完全符合你的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.