简体   繁体   English

C#StreamReader多次读取数据

[英]C# streamreader read data multiple times

I have this code: 我有以下代码:

  using (StreamReader csvreader = new StreamReader(fuFiles.FileContent))
            {
                while (!csvreader.EndOfStream)
                {
                  //reading data
                }
            }

I'm using this in two different functions. 我在两个不同的功能中使用它。 In the first function the EndOfStream value is false and the data can be read properly. 在第一个函数中,EndOfStream的值为false,可以正确读取数据。 In the second function this same kind of code says that EndOfStream is true and I'm not able to read data. 在第二个函数中,相同类型的代码表示EndOfStream为true,而我无法读取数据。 I'm creating streamreader objects independently. 我正在独立创建streamreader对象。

Edit 编辑

I'm adding one more line of explanation, when I'm commenting the first method then I'm able to read the data in the second method. 我添加了另一条解释,当我评论第一种方法时,便能够读取第二种方法中的数据。

Is there anything I'm doing wrong? 我做错了什么吗?

There are only two constructors for StreamReader that take one parameter. StreamReader只有两个带有一个参数的构造函数。 Since "FileContent" is probably not a string, it must be a Stream of some kind. 由于“ FileContent”可能不是字符串,因此它必须是某种Stream。 The first time it is read from it is left at the end. 第一次从中读取它是在末尾。 Therefore you must either reset it to the beginning (if it allows that), make a copy before reading, or get a new one created. 因此,您必须将其重置为开头(如果允许),在读取之前进行复制或创建一个新副本。

Based on the variable names in the code you provided, it looks like you're passing the contents of a file to the StreamReader constructor. 根据您提供的代码中的变量名称,看起来您正在将文件的内容传递给StreamReader构造函数。 However, that constructor takes the path to the file to read - not the contents of the file. 但是,该构造函数采用要读取的文件的路径-而不是文件的内容。

You can use the StringReader class to use a stream to read from a string, if that is what you want to do. 您可以使用StringReader类使用流从字符串中读取(如果要这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM