我正在從檔案中讀取,我試圖跳過前兩行并從第三行開始讀取。我檢查了其他已回答的問題,但由于某種原因,它們都沒有在統一方面發揮作用。我收到了幾個錯誤,但是它應該可以作業。
StreamReader reader = new StreamReader(path);
string line = "";
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
....
}
uj5u.com熱心網友回復:
如果我理解正確,我們可以嘗試使用File.ReadAllLineswhich 將從您的檔案文本中回傳所有文本內容行,然后從第三行開始讀取(陣列從 0 開始,因此第三行可能是contents[2])。
var contents = File.ReadAllLines(path);
for (int i = 2; i < contents.Length; i )
{
string[] words = contents[i].Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
}
如果我們知道Encoding檔案的名稱,我們可以嘗試設定Encoding為第二個引數File.ReadAllLines
uj5u.com熱心網友回復:
與 D-Shih 的解決方案類似,一個 using File.ReadLines,它回傳一個IEnumerable<string>:
var lines = File.ReadLines(path);
foreach (string line in lines.Skip(2))
{
string[] words = line.Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
// etc.
}
這種方法優于 D-Shih 的好處是您不必一次將整個檔案讀入記憶體來處理它,因此該解決方案類似于您現有解決方案對StreamReader.
作為直接解決問題的解決方案,您只需要ReadLine在進入回圈之前呼叫兩次(跳過這兩行),盡管我認為上面的解決方案更清晰:
using (StreamReader reader = new StreamReader(path))
{
string line = "";
// skip 2 lines
for (int i = 0; i < 2; i)
{
reader.ReadLine();
}
// read file normally
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
....
}
}
請注意,我還將閱讀器包裝在 a 中using,以便在回圈完成或拋出例外的情況下關閉并處理檔案句柄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482434.html
上一篇:在Dapper中異步查詢多個結果
