C# 从文本文件中删除特定行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1245243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:09:43  来源:igfitidea点击:

Delete specific line from a text file?

c#text-files

提问by Goober

I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.

我需要从文本文件中删除一个确切的行,但我一生都无法锻炼如何执行此操作。

Any suggestions or examples would be greatly appreciated?

任何建议或示例将不胜感激?

Related Questions

相关问题

Efficient way to delete a line from a text file (C#)

从文本文件中删除一行的有效方法(C#)

采纳答案by Sean Bright

If the line you want to delete is based on the content of the line:

如果要删除的行是基于行的内容:

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);
        }
    }
}

Or if it is based on line number:

或者,如果它基于行号:

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);
        }
    }
}

回答by Aric TenEyck

The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.

最好的方法是在文本模式下打开文件,用 ReadLine() 读取每一行,然后用 WriteLine() 将其写入新文件,跳过要删除的一行。

There is no generic delete-a-line-from-file function, as far as I know.

据我所知,没有通用的从文件中删除一行的函数。

回答by Steve Gilham

  1. Read and remember each line

  2. Identify the one you want to get rid of

  3. Forget that one

  4. Write the rest back over the top of the file

  1. 阅读并记住每一行

  2. 确定你想摆脱的那个

  3. 忘记那个

  4. 将其余部分写回文件顶部

回答by Darin Dimitrov

One way to do it if the file is not very big is to load all the lines into an array:

如果文件不是很大,一种方法是将所有行加载到一个数组中:

string[] lines = File.ReadAllLines("filename.txt");
string[] newLines = RemoveUnnecessaryLine(lines);
File.WriteAllLines("filename.txt", newLines);

回答by DataDink

You can actually use C# generics for this to make it real easy:

你实际上可以使用 C# 泛型来使它变得非常简单:

        var file = new List<string>(System.IO.File.ReadAllLines("C:\path"));
        file.RemoveAt(12);
        File.WriteAllLines("C:\path", file.ToArray());

回答by DataDink

Are you on a Unix operating system?

您使用的是 Unix 操作系统吗?

You can do this with the "sed" stream editor. Read the man page for "sed"

您可以使用“sed”流编辑器执行此操作。阅读“sed”的手册页

回答by DataDink

What? Use file open, seek position then stream erase line using null.

什么?使用文件打开,查找位置,然后使用 null 流擦除行。

Gotch it? Simple,stream,no array that eat memory,fast.

明白了吗?简单,流,没有占用内存的数组,速度快。

This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en

这项工作在 vb.. 示例搜索行culture=id,其中culture 是namevalue,id 是value,我们想将其更改为culture=en

Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
    line = lineinput(1)
    dim namevalue() as string = split(line, "=")
    if namevalue(0) = "line name value that i want to edit" then
        currentpos = seek(1)
        fileclose()
        dim fs as filestream("test.ini", filemode.open)
        dim sw as streamwriter(fs)
        fs.seek(currentpos, seekorigin.begin)
        sw.write(null)
        sw.write(namevalue + "=" + newvalue)
        sw.close()
        fs.close()
        exit while
    end if
    msgbox("org ternate jua bisa, no line found")
end while

that's all..use #d

这就是全部..使用#d

回答by Muhammad Faizan Khan

No rocket scien code require .Hope this simple and short code will help.

不需要火箭科学代码。希望这个简单而简短的代码会有所帮助

List linesList = File.ReadAllLines("myFile.txt").ToList();            
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());

ORuse this

或者使用这个

public void DeleteLinesFromFile(string strLineToDelete)
    {
        string strFilePath = "Provide the path of the text file";
        string strSearchText = strLineToDelete;
        string strOldText;
        string n = "";
        StreamReader sr = File.OpenText(strFilePath);
        while ((strOldText = sr.ReadLine()) != null)
        {
            if (!strOldText.Contains(strSearchText))
            {
                n += strOldText + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(strFilePath, n);
    }

回答by Kurt Van den Branden

This can be done in three steps:

这可以通过三个步骤来完成:

// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);

// 2. Empty the file
File.WriteAllText(path, String.Empty);

// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
{
    foreach (string s in readText)
    {
        if (!s.Equals(lineToBeRemoved))
        {
            writer.WriteLine(s);
        }
    }
}