c# - 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 返回一个空字符串,所以下一行捕获了一个异常。我在这里看到过类似的问题,但没有一个能帮助我具体找出我的代码出了什么问题,所以如果你们有任何帮助,将不胜感激。
解决方案
推荐阅读
- sql - 插入第一个表后如何使用一些相同的信息自动更新第二个表
- loopbackjs - 使用提供者在拦截器中传递自定义参数
- javascript - 创建自定义输入字段
- svg - SVG feImage 过滤器剪辑中风 - 如何阻止它?
- javascript - 如果满足条件,则在 JavaScript 中合并数组中的对象
- botframework - 如何添加一个可以关闭网络聊天页面的按钮?
- ruby-on-rails - Rails webpacker 正在加载以前删除的控制器
- datagrid - 如何在 WPF DataGrid 中禁用 CTRL 键盘
- php - 如何使用 PHP 更改 Excel 单元格日期
- android - 如何修复带有房间的片段中的 java.lang.NullPointerException