首页 > 解决方案 > C# StreamReader.ReadLine() 在循环中返回一个空字符串

问题描述

我正在尝试在 C# 中创建一个代码来读取文件中的一些数字并将它们添加到矩阵中,以便我可以使用它们。这是文件的一些内容:

ID   X   Y   Z   U Eps 100   V Eps 100   W Eps 100 
1204    101.25  0   0   0   0   0   
1205    101.25  0.0321000840330112  4.473425    0.00200077306900823 -0.00292669254354999    -0.00514929334513621    
1206    101.25  0.0642001680660224  8.94685 0.0065549384905434  -

因此,我基本上使用 StreamReader ReadLine 来获取文件中的行,然后对于每一行我将其拆分并存储在矩阵中,这是代码:

// Get the path of the file
string path = dlg.FileName;
tb.Text = path;

// Get the lenght of the file
string[] allFile = File.ReadAllLines(path);  
int lenght = allFile.Length;
MessageBox.Show(File.ReadAllText(path));

// Initialize reading
StreamReader sr = new StreamReader(path);
string line = sr.ReadLine(); // Read first line, discarted
line = sr.ReadLine();

// Array of numbers in a line
string[] bits = line.Split();

// Matrix containing all the points
float[,] points = new float[lenght, 7];
for (int i = 0; i < lenght; i++)
{
    for (int j = 0; j < 7; j++)
    {
        points[i, j] = float.Parse(bits[j]);
    }
    line = sr.ReadLine();
    bits = line.Split();
}

所以,这段代码不起作用,经过一些测试,我意识到 for 循环中的 sr.ReadLine 返回一个空字符串,所以下一行捕获了一个异常。我在这里看到过类似的问题,但没有一个能帮助我具体找出我的代码出了什么问题,所以如果你们有任何帮助,将不胜感激。

标签: c#streamreader

解决方案


推荐阅读