我有一个使用Compact Framework 3.5
重写的Windows窗体应用程序。在原始应用程序中,我有一段代码,我曾经在文件中读取并跳过前4行。
这是可以正常工作的代码块:
var openFile = File.OpenText(fullFileName);
var fileEmpty = openFile.ReadLine();
if (fileEmpty != null)
{
var lines = File.ReadAllLines(fullFileName).Skip(4); //Will skip the first 4 then rewrite the file
openFile.Close();//Close the reading of the file
File.WriteAllLines(fullFileName, lines); //Reopen the file to write the lines
openFile.Close();//Close the rewriting of the file
}
我不得不重写上面的代码,因为它不能在Compact Framework中这样使用。
这是我的代码:
var openFile = File.OpenText(fullFileName);
var fileEmpty = openFile.ReadLine();
if (fileEmpty != null)
{
var sb = new StringBuilder();
using (var sr = new StreamReader(fullFileName))
{
string line1;
// Read and display lines from the file until the end of
// the file is reached.
while ((line1 = sr.ReadLine().Skip(4).ToString()) != null) //Will skip the first 4 then rewrite the file
{
sb.AppendLine(line1);
}
}
然而,当我运行上面的操作时,我收到错误(while ((line1 = sr.ReadLine().Skip(4).ToString()) != null)
)ArgumentNullException未处理且Value不能为null。
有人可以告诉我如何在紧凑的框架中做到这一点吗?
答案 0 :(得分:2)
由于sr.ReadLine()
返回一个字符串,这将跳过字符串中的前四个字符,将其余字符作为字符数组返回,然后在其上调用ToString()
...而不是你想要的。
sr.ReadLine().Skip(4).ToString()
您获得ArgumentNullException
的原因是sr.ReadLine()
最终返回null
字符串,并且当您尝试跳过null
字符串的前四个字符时通过查看Skip()
:
public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count)
{
if (source == null)
throw new ArgumentNullException("source");
return SkipIterator<TSource>(source, count);
}
保持大部分代码相同,你可以只阅读前几行而不对它们做任何事情(假设你的文件中肯定至少有4行)。
using (var sr = new StreamReader(fullFileName))
{
// read the first 4 lines but do nothing with them; basically, skip them
for (int i=0; i<4; i++)
sr.ReadLine();
string line1;
while ((line1 = sr.ReadLine()) != null)
{
sb.AppendLine(line1);
}
}