[在C#中使用“ ReadToEnd()”读取流“ Stream”的内容

问题描述 投票:0回答:1

我有一个函数,其输入参数的类型为“ stream”。我想读取此流的内容,并将其与文件的内容进行比较。已经完成以下操作:

        public bool func(Stream stream, string tempFilePath, string dstFilePath)
        {
            string[] File1 = File.ReadAllLines(tempFilePath);
            stream.Seek(0, SeekOrigin.Begin); 
            int line = 0;
            StreamReader reader = new StreamReader(stream);
            string[] File2 = reader.ReadToEnd().Split(
                                                        new[] { "\r\n", "\r", "\n" },
                                                        StringSplitOptions.None
                                                    );
            while (lineNum < File1.Length)
                  {
                    if (astFile2[line] != astFile1[line])
                        break;

                     line++;
                   }
             bool ret = line == astFile1.Length && line == astFile2.Length - 1;
             if (ret )
               {
                using (var dstFile = new FileStream(dstFilePath, FileMode.Create, FileAccess.Write))
                   {
                      stream.CopyTo(dstFile );
                    }
                }
              return ret;
        }

问题是,我无法再使用以下命令获取变量“ stream”的内容:“ stream.CopyTo(dstFile);”内容为空!

使用stream.Seek(0, SeekOrigin.Begin);的流的“位置”正确。我在stream.Seek(0, SeekOrigin.Begin);行之后使用了ReadToEnd()命令,但没有帮助。我也使用了stream.Position = 0,也没有帮助。因此,我认为按位置应该没有问题。

此代码遗漏了什么?为什么ReadToEnd()命令导致清空stream

为了测试,我还做了以下工作:

  string[] File2 = reader.ReadToEnd().Split(
                                            new[] { "\r\n", "\r", "\n" },
                                            StringSplitOptions.None
                                        );


  stream.Position = 0;
   string[] File3 = reader.ReadToEnd().Split(
                                            new[] { "\r\n", "\r", "\n" },
                                            StringSplitOptions.None
                                        );

“ File3”的内容仍然为空!

c# stream
1个回答
0
投票

我总是确保在执行ReadToEnd()之前先调用stream.Flush()。

© www.soinside.com 2019 - 2024. All rights reserved.