我有一個文本文件,其中包含一個固定長度的表,我試圖解析。但是,文件的開頭是關於何時生成此表的一般信息(IE時間,數據等)。閱讀流與2個不同的閱讀器
要閱讀本文,我試圖製作一個FileStream
,然後用StreamReader
讀取此文件的第一部分。我從文檔的頂部解析出我需要的內容,然後在完成後將流的位置設置爲結構化數據的第一行。
然後,我將一個TextFieldParser
附加到流(具有適當的固定長度表設置),然後嘗試讀取文件。在第一行中,它失敗,並在ErrorLine
屬性中列出了表的第三行的後半部分。我通過它,它是在第一行閱讀,但ErrorLine
財產建議,否則。
調試時,我發現如果我在將TextFieldParser
附加到流中後嘗試使用我的StreamReader.ReadLine()
方法,則前兩行顯示正常。但是,當我讀取第三行時,它將返回一行,以第三行的前半部分開頭(並在ErrorLine
中的文本所在的位置停止)會附加文檔中稍後的某個部分。如果我在附上TextFieldParser
之前嘗試此操作,它會讀取所有3行。
我有一種感覺,這與我將2個讀者綁定到同一個流中有關。我不知道如何用結構化部分和非結構化部分來讀取它,而不需要自己標記線條。我可以做到這一點,但我認爲我不是第一個想要單獨閱讀流的一部分的人,以及另一個流的後面部分。
爲什麼它會跳過這樣的情況,以及如何閱讀不同格式的文本文件?
例如:對於這個簡單的例子定製
Date: 3/1/2013
Time: 3:00 PM
Sensor: Awesome Thing
Seconds X Y Value
0 5.1 2.8 55
30 4.9 2.5 33
60 5.0 5.3 44
代碼:
Boolean setupInfo = true;
DataTable result = new DataTable();
String[] fields;
Double[] dFields;
FileStream stream = File.Open(filePath,FileMode.Open);
StreamReader reader = new StreamReader(stream);
String tempLine;
for(int j = 1; j <= 7; j++)
{
result.Columns.Add(("Column" + j));
}
//Parse the unstructured part
while(setupInfo)
{
tempLine = reader.ReadLine();
if(tempLine.StartsWith("Date: "))
{
result.Rows.Add(tempLine);
}
else if (tempLine.StartsWith("Time: "))
{
result.Rows.Add(tempLine);
}
else if (tempLine.StartsWith("Seconds")
{
//break out of this loop because the
//next line to be read is the unstructured part
setupInfo = false;
}
}
//Parse the structured part
TextFieldParser parser = new TextFieldParser(stream);
parser.TextFieldType = FieldType.FixedWidth;
parser.HasFieldsEnclosedInQuotes = false;
parser.SetFieldWidths(10, 10, 10, 10);
while (!parser.EndOfData)
{
if (reader.Peek() == '*')
{
break;
}
else
{
fields = parser.ReadFields();
if (parseStrings(fields, out dFields))
{
result.Rows.Add(dFields);
}
}
}
return result;
你可以發佈您的代碼?這將有助於識別問題 – VladL 2013-03-01 22:58:12
@VladL好的,我添加了針對該示例的代碼。有一點需要注意的是,我將數據添加到「DataTable」並從此函數返回。 – Xantham 2013-03-01 23:09:44