[英]c# reading from a text file
我正在閱讀具有某種格式的文本文件。 我跳過了前兩行,然后讀取了firstname,secondname,然后創建了一個firstname,secondname的列表。 一切正常,但最后一行為空時,我的程序停止工作並給出錯誤。 如何避免whiltespace,以便我的程序不停止我的代碼,是:
public void Read(string filename, List<Person> person)
{
using (StreamReader sr = new StreamReader(filename))
{
sr.ReadLine();
sr.ReadLine();
while (!sr.EndOfStream)
{
FirstName= sr.EndOfStream ? string.Empty : sr.ReadLine();
LastName= sr.EndOfStream ? string.Empty : sr.ReadLine();
person.Add(new Person(FirstName, LastName));
}
}
}
文件格式為
Students Data
Description
FirstName
LastName
FirstName
LastName
FirstName
LastName
FirstName
LastName
出問題了,無論文檔是否有下一行,都將執行sr.ReadLine()
,因此它可能返回null(如果您用完了所有行),只需檢查sr.ReadLine()
返回null
public void Read(string filename, List<Person> person)
{
using (StreamReader sr = new StreamReader(filename))
{
sr.ReadLine();
sr.ReadLine();
while (!sr.EndOfStream)
{
String FirstName = sr.ReadLine() ?? "-not defined-";
String LastName = sr.ReadLine() ?? "-not defined-";
person.Add(new Person(FirstName, LastName));
}
}
}
您可以為StreamReader類創建一個適配器,如下所示
public class NoBlankStreamReader : StreamReader
{
public NoBlankStreamReader(FileStream fs) : base(fs) { }
private bool IsBlank(string inString)
{
if (!string.IsNullOrEmpty(inString)) inString = inString.Trim();
return string.IsNullOrEmpty(inString);
}
public override string ReadLine()
{
string result= base.ReadLine();
while (result!=null && IsBlank(result))
result = base.ReadLine();
return result;
}
}
然后像這樣使用:
using (FileStream fs=File.OpenRead(@"test.txt"))
using (TextReader reader = new NoBlankStreamReader(fs))
{
while (reader.Peek() > -1)
Console.WriteLine(reader.ReadLine());
}
或者您可以看到該帖子:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.