我正在创建一个函数,它将从一个StreamReader获取行数,不包括注释(以‘//’开头的行)和新行。
这是我的密码:
private int GetPatchCount(StreamReader reader)
{
int count = 0;
while (reader.Peek() >= 0)
{
string line = reader.ReadLine();
if (!String.IsNullOrEmpty(line))
{
if ((line.Length > 1) && (!line.StartsWith("//")))
{
count++;
}
}
}
return count;
}我的StreamReader的数据是:
// Test comment但我得到了一个错误,“对象引用没有设置为对象的实例。”有办法纠正这个错误吗?
编辑发现,当的StreamReader为null时,就会发生这种情况。因此,关于musefan和Smith先生的建议代码,我想出了以下内容:
private int GetPatchCount(StreamReader reader, int CurrentVersion)
{
int count = 0;
if (reader != null)
{
string line;
while ((line = reader.ReadLine()) != null)
if (!String.IsNullOrEmpty(line) && !line.StartsWith("//"))
count++;
}
return count;
}谢谢你的帮助!
发布于 2013-04-22 15:17:24
没有必要使用Peek(),这可能也是问题所在。你可以这么做:
string line = reader.ReadLine();
while (line != null)
{
if (!String.IsNullOrEmpty(line) && !line.StartsWith("//"))
{
count++;
}
line = reader.ReadLine();
}当然,如果您的StreamReader为null,那么您就有一个问题,但是仅用示例代码还不足以确定这一点--您需要调试它。应该有大量的调试信息供您计算出哪个对象实际上是空的。
发布于 2013-04-22 15:16:49
听起来你的reader对象是null
通过执行以下操作,可以检查读取器是否为空:
if (reader == null) {
reader = new StreamReader("C:\\FilePath\\File.txt");
} 发布于 2013-04-22 15:26:46
musefan建议的代码的更简洁的变体;只是一个ReadLine()代码。+1建议移除长度检查。
private int GetPatchCount(StreamReader reader)
{
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
if (!String.IsNullOrEmpty(line) && !line.StartsWith("//"))
count++;
return count;
}https://stackoverflow.com/questions/16150606
复制相似问题