如何从文本文件的开头读取StreamReader

本文关键字:开头 读取 StreamReader 文件 文本 | 更新日期: 2023-09-27 18:28:58

我创建了一个streamReader,但第一个"ReadLine()"读取的是文件中的第14行,而不是第一行,我不知道为什么会这样。

我的代码是:

StreamReader reader = new StreamReader("argus-BIG.txt");  
//create array to hold data values
string[] branchData = new string[11];
//get 11 lines of branch data file and store in an array
for (int i = 0; i < 11; i++)
{
    branchData[i] = reader.ReadLine();
}            
//new instance of Branch Class
Branch tempBranch = new Branch();
//set branch values from branchData array
tempBranch.setBranchID(branchData[0]);
tempBranch.setBranchNickname(branchData[1]);
tempBranch.setBranchAddressNo(branchData[2]);
tempBranch.setBranchAddressStreet(branchData[3]);
tempBranch.setBranchAddressCity(branchData[4]);
tempBranch.setBranchAddressCountry(branchData[5]);
tempBranch.setBranchAddressPostCode(branchData[6]);            
tempBranch.setNearestBranch1(branchData[7]);
tempBranch.setNearestBranch2(branchData[8]);
tempBranch.setNearestBranch3(branchData[9]);
tempBranch.setNoCategories(Convert.ToInt32(branchData[10]));

我写了一个测试应用程序,它起作用了,然后把代码(看起来和我一模一样)复制粘贴回我的主程序,它就起作用了。感谢您的帮助

如何从文本文件的开头读取StreamReader

这应该是有效的,我猜在这一过程中还会发生其他事情。一旦你打开一个阅读器,它就会向下移动,如果你想让它回到顶部阅读,就必须重置。也许你的引用在其他地方打开了(但这是假设发布的代码发生了一些没有发布的事情),或者在这段代码之前使用了?

然而,你总是可以把位置推到顶部来验证这个理论。如果在这段代码之后,你仍然在第14行,那么它可能是文件本身?

reader.DiscardBufferedData(); 
reader.BaseStream.Seek(0, SeekOrigin.Begin); 
reader.BaseStream.Position = 0;