Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否从文本文件中删除特定行?_C#_Text Files - Fatal编程技术网

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

C# 是否从文本文件中删除特定行?,c#,text-files,C#,Text Files,我需要从一个文本文件中删除一行,但我不能用我的一生去锻炼如何去做这件事 如有任何建议或示例,将不胜感激 相关问题 最好的方法是以文本模式打开文件,用ReadLine()读取每一行,然后用WriteLine()将其写入新文件,跳过要删除的一行 据我所知,没有通用的从文件中删除一行的功能 阅读并记住每一行 确定你想要摆脱的一个 的 忘了那个吧 把剩下的写在上面 档案 如果文件不是很大,一种方法是将所有行加载到一个数组中: string[] lines = File.ReadAllLines("fil

我需要从一个文本文件中删除一行,但我不能用我的一生去锻炼如何去做这件事

如有任何建议或示例,将不胜感激

相关问题


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

据我所知,没有通用的从文件中删除一行的功能

  • 阅读并记住每一行

  • 确定你想要摆脱的一个 的

  • 忘了那个吧

  • 把剩下的写在上面 档案


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

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

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

    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);
            }
        }
    }
    
    或者,如果是基于行号:

    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);
            }
        }
    }
    
    实际上,您可以使用C#泛型来实现这一点,使其变得非常简单:

            var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
            file.RemoveAt(12);
            File.WriteAllLines("C:\\path", file.ToArray());
    
    var file=新列表(System.IO.file.ReadAllLines(“C:\\path”);
    文件删除(12);
    writeAllines(“C:\\path”,File.ToArray());
    
    您使用的是Unix操作系统吗

    您可以使用“sed”流编辑器执行此操作。阅读“sed”的手册页什么? 使用文件打开,查找位置,然后使用null流擦除行

    明白了吗?简单、流式、无阵列、快速消耗内存

    这项工作是在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
    

    仅此而已..请使用#d

    希望这段简单而简短的代码可以

    使用


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

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

    我关心文件的原始结束行字符(“\n”或“\r\n”),并希望在输出文件中保留它们(而不是像其他答案那样使用当前环境的字符覆盖它们)。因此,我编写了自己的方法来读取一行而不删除结束行字符,然后在我的
    DeleteLines
    方法中使用它(我想要删除多行的选项,因此需要使用一组行号来删除)

    DeleteLines
    实现为
    FileInfo
    扩展和
    ReadLineKeepNewLineChars
    StreamReader扩展(但显然您不必保持这种方式)

    公共静态类FileInfoExtensions
    {
    公共静态FileInfo DeleteLines(此FileInfo源、ICollection行号、字符串targetFilePath)
    {
    var-lineCount=1;
    使用(var streamReader=newstreamreader(source.FullName))
    {
    使用(var streamWriter=newstreamwriter(targetFilePath))
    {
    弦线;
    而((line=streamReader.ReadLineKeepNewLineChars())!=null)
    {
    如果(!lineNumbers.Contains(lineCount))
    {
    streamWriter.Write(行);
    }
    lineCount++;
    }
    }
    }
    返回新文件信息(targetFilePath);
    }
    }
    公共静态类StreamReaderExtensions
    {
    private const char EndOfFile='\uffff';
    /// 
    ///读取一行,类似于ReadLine方法,但保留任何
    ///新行字符(例如“\r\n”或“\n”)。
    /// 
    公共静态字符串ReadLineKeepNewLineChars(此StreamReader源)
    {
    if(source==null)
    抛出新ArgumentNullException(nameof(source));
    char ch=(char)source.Read();
    if(ch==EndOfFile)
    返回null;
    var sb=新的StringBuilder();
    while(ch!=EndOfFile)
    {
    某人附加(ch);
    如果(ch='\n')
    打破
    ch=(char)source.Read();
    }
    使某人返回字符串();
    }
    }
    
    +1比缓存所有行然后写回而不删除其中一行要好。您如何识别这一行?根据它的位置?按其确切文本?通过包含的单词?11年前询问过,但没有一个答案真正尊重原始文件的结束行字符(例如“\r\n”或“\n”),而是使用当前环境的新行字符重写:-(是的,只要文件可以轻松地完全存储在内存中,这是一种很好的简单方法。当然,只有当文件内容可以放入内存时,这种方法才适用,否则必须使用Aric TenEyck提出的“流”方法和临时文件。
    删除不必要的基线()
    看起来要删除任何一行吗?这对大文件来说不是很好,但聪明的话就更少了。问题是如果文件不能放入内存中…忘记那一行吧?你怎么能做到这一点呢?@user189590:虽然对VB来说很好,但当标签中明确提到c#时,这是没有用的。简短、甜美、优雅。非常有魅力,谢谢!如果要基于某行中的某个值删除某个特定行,则此选项尤其有用。
    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);
        }
    
    // 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);
            }
        }
    }