Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将文件流更改为字符串?_C#_Filestream - Fatal编程技术网

C# 如何将文件流更改为字符串?

C# 如何将文件流更改为字符串?,c#,filestream,C#,Filestream,在下面的代码中,如何将流更改为接收字符串变量 // open dictionary file FileStream fs = new FileStream(dictionaryPath, FileMode.Open, FileAccess.Read, FileShare.Read); StreamReader sr = new StreamReader(fs, Encoding.UTF8); // read line by lin

在下面的代码中,如何将流更改为接收字符串变量

        // 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]" :

                    ...
                    ...
                    ...

看起来您只需要调用ReadLine,在这种情况下,您可以将sr的类型更改为TextReader

然后,可以将StreamReader替换为,并传入要使用的字符串:

TextReader sr = new StringReader(inputString);

你是说?它创建一个读取字符串内容的流。

如果您有一个字符串,并且希望像读取流一样从中读取,请执行以下操作:

byte[] byteArray = Encoding.ASCII.GetBytes(theString);
MemoryStream stream = new MemoryStream(byteArray);

我的建议。。尽可能远离溪流

在这种情况下,您可以

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

希望这有帮助

首先,你尝试过什么,你的意思是你想要流式传输一个字符串…这实际上已经是一个流了…猜猜看,你想用一个现有的字符串替换文件流,然后从该字符串读取吗?@DanPichelman:是的,这正是我想做的。它似乎是“File.ReadAllText”、“File.ReadLines”。。。在整个读取期间锁定文件,使其对其他读取器不可用。在我的服务器中,我经常收到文件被锁定的错误,会话将失败,将其更改为流式文件共享。读取修复了该问题。所以我想哪种方法更好取决于具体情况。