本文的sample code來自 http://stackoverflow.com/questions/1245243/delete-specific-line-from-a-text-file

如果你要刪除特定內容的某一行,sample code如下

string line = null;
string line_to_delete = "the line i want to delete";

using (StreamReader reader = new StreamReader("C:\\input")) {
    using (StreamWriter writer = new StreamWriter("C:\\output")) {
        while ((line = reader.ReadLine()) != null) {
            if (String.Compare(line, line_to_delete) == 0)
                continue;

            writer.WriteLine(line);
        }
    }
}

如果你是要刪除某特定行數的內容,sample code如下

string line = null;
int line_number = 0;
int line_to_delete = 12;

using (StreamReader reader = new StreamReader("C:\\input")) {
    using (StreamWriter writer = new StreamWriter("C:\\output")) {
        while ((line = reader.ReadLine()) != null) {
            line_number++;

            if (line_number == line_to_delete)
                continue;

            writer.WriteLine(line);
        }
    }
}
arrow
arrow
    文章標籤
    c# delete a line from text file
    全站熱搜

    痞客興 發表在 痞客邦 留言(0) 人氣()