将多行文本文件解析为多个变量

时间:2014-01-18 22:43:08

标签: c# asp.net .net parsing text-files

我有点陷入某个特定问题。我在.NET中工作,需要将多行文本文件解析为多个变量。到目前为止,据我所知,我已经阅读了第一行。这是文本文件的样子:

1/10/2014 1,2,3
1 0 0
1 1 0
1 2 0
1 3 0
1 4 0
1 5 0
1 6 0
1 7 0
1 8 0

这是我的代码第一行的代码 - 它应该是拉出日期(现在,它不是拉出日期,它今天分配)和“1,2,3”,然后取代逗号为“1 2 3”的空格。对于其余的,每一行中的每个数字都应该是它自己的变量,这就是我被困住的地方。我只需要为每个后续行拾取前导“1”作为一个变量(它将始终为0或1),并且每个中的第二个数字是层数(那些将始终为0-8),并且每行中的最后一个数字,现在都是“0”,都是单独的变量,并且会有所不同。

string filePath = ConfigurationSettings.AppSettings["FileName.txt"];
StreamReader reader = null;
FileStream fs = null;
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
reader = new StreamReader(fs);
string line = null;
line = reader.ReadLine();
string[] lineInfo = line.Split(' ');
string NumbersTemp = lineInfo[1];
string numbers = NumbersTemp.Replace(","," ");
string date = DateTime.Today.ToString("MM/dd/yyyy");

正如你所看到的,我对变量的了解并不是很远,我甚至不确定这是否能够按照我迄今为止的方式正常工作。这不是错误的,但它并不完整。任何有助于获得这些变量的帮助都将非常受欢迎。

1 个答案:

答案 0 :(得分:3)

StreamReader.ReadLine读取一行。您只使用一次。使用循环:

string date = DateTime.Today.ToString("MM/dd/yyyy");
string filePath = ConfigurationSettings.AppSettings["FileName.txt"];
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using(var reader = new StreamReader(fs))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        string[] lineInfo = line.Split(' ');
        string NumbersTemp = lineInfo[1];
        string numbers = NumbersTemp.Replace(",", " ");
        // ...
    }
}

我还使用using语句来确保即使发生错误也会处置所有非托管资源。

相关问题