【问题标题】:StreamReader read file and StreamWriter write that result omitting first line?StreamReader 读取文件和 StreamWriter 写入结果省略第一行?
【发布时间】:2014-04-03 18:02:30
【问题描述】:

使用以下代码:

string lines = "";
using (StreamReader sr = new StreamReader(@"file.txt"))
{
    lines = sr.ReadLine();
}
using (StreamWriter writer = new StreamWriter(@"file.txt"))
{
    writer.Write(lines); // Change this to skip the first line
}

如何让它重写除第一行之外的所有内容?

【问题讨论】:

  • 您的代码完全错误。 lines 的类型为 string... 它不是一个数组。另外,你打电话给ReadLine...,因为它不是复数...读取单行...
  • 我不明白你要做什么。你只看了一行,如果你跳过它,那么你什么都没有?

标签: c# string streamreader streamwriter


【解决方案1】:
var allLinesExceptFirstOne = System.IO.File.ReadAllLines(filename).Skip(1).ToList();

【讨论】:

    【解决方案2】:

    也许你可以试试这个:

    var lines =  File.ReadLines("file.txt").Skip(1).ToList();
    File.WriteAllLines("file.txt",lines);
    

    它将除第一行之外的所有行写入您的文件并替换您的文件内容。所以基本上它会从您的文件中删除第一行。

    【讨论】:

    • 我以前使用过这种方法,但我一直收到错误An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll Additional information: The process cannot access the file 'file.txt' because it is being used by another process.,这就是我切换到 StreamReader/StreamWriter 的原因。
    • @Keavon okey 然后尝试分离两种方法
    猜你喜欢
    • 2019-02-26
    • 2015-09-17
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2012-02-22
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多