在具有以下代码中,如何将流更改为接收字符串变量?
// open dictionary file
FileStream fs = new FileStream(dictionaryPath, FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
// read line by line
while (sr.Peek() >= 0)
{
string tempLine = sr.ReadLine().Trim();
if (tempLine.Length > 0)
{
// check for section flag
switch (tempLine)
{
case "[Copyright]" :
case "[Try]" :
case "[Replace]" :
case "[Prefix]" :
...
...
...
答案 0 :(得分:1)
看起来您只需要致电ReadLine()
- 在这种情况下,您可以将sr
的类型更改为TextReader
。
然后,您可以将StreamReader
替换为StringReader并传入您要使用的字符串:
TextReader sr = new StringReader(inputString);
答案 1 :(得分:1)
我的建议......“如果可以的话,远离溪流”
在这种情况下,您可以
1)读取字符串变量中的所有文件;
2)在行尾字符(\r\n
)
3)执行简单的foreach
循环并将switch语句放入其中
小例子:
string dictionaryPath = @"C:\MyFile.ext";
string dictionaryContent = string.empty;
try // intercept file not exists, protected, etc..
{
dictionaryContent = File.ReadAllText(dictionaryPath);
}
catch (Exception exc)
{
// write error in log, or prompt it to user
return; // exit from method
}
string[] dictionary = dictionaryContent.Split(new[] { "\r\n" }, StringSplitOptions.None);
foreach (string entry in dictionary)
{
switch (entry)
{
case "[Copyright]":
break;
case "[Try]":
break;
default:
break;
}
}
希望这有帮助!
答案 2 :(得分:0)
你的意思是StringReader吗?它创建一个读取字符串内容的流。
答案 3 :(得分:0)
如果你有一个字符串,你想从中读取它就像一个流:
byte[] byteArray = Encoding.ASCII.GetBytes(theString);
MemoryStream stream = new MemoryStream(byteArray);