删除多个文件中的行

时间:2014-07-26 04:55:05

标签: c# file line

我要删除位于我的文件中的旧标题,该标题由3行文本组成。 到目前为止,我完成了这项工作,但我不能让这项工作超过一个文件...

我尝试了什么:

string line = null;
string line_to_delete =     "-------------------------------" 
    + Environment.NewLine + "-- VSO2 CE " 
    + Environment.NewLine + "-------------------------------";
foreach (string file in Directory.GetFiles("dir"))
{
    using (StreamReader reader = new StreamReader(file))
    {
        using (StreamWriter writer = new StreamWriter(file))
        {
            while ((line = reader.ReadLine()) != null)
            {
                if (String.Compare(line, line_to_delete) == 0)
                continue;

                writer.WriteLine(line);
            }
        }
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分:0)

如何重构这样的事情:

const string Delim = "-------------------------------";
const string SomeText = "-- VSO2 CE ";
foreach (string filePath in Directory.GetFiles("dir")) 
{
    var first3Lines = File.ReadLines(filePath).Take(3).ToList(); 
    if(first3Lines.First() == Delim && 
       first3Lines.Last() == Delim && 
       first3Lines[1]==SomeText)
    {
        //this file's first 3 lines matches what you want.
        //now write something somehow.
        //it wasn't super clear what you want to write or do.     
        //leave a comment if you want help with that.
        DeleteLines(filePath, 3);
    }                    
}


private void DeleteLines(string filePath, int numLines) {

    using (StreamReader reader = new StreamReader(filePath))
    using (StreamWriter writer = new StreamWriter(filePath + "-new.txt")) {
        while (numLines-- > 0) { reader.ReadLine(); }
        string line;
        while ((line = reader.ReadLine()) != null)
            writer.WriteLine(line);
    }
}

答案 1 :(得分:0)

您正在使用以下方法:line = reader.ReadLine(),它将读取该行(直到它的结尾),并且永远不会匹配包含3行的line_to_delete

您认为它如何匹配它们? :)

如果您知道它们是标题,并且它们始终位于顶部,那么如何使用File.ReadAllLines().Skip(3),然后将其写回文件?