从文本文件中删除一行的有效方法 [英] Efficient way to delete a line from a text file

查看:55
本文介绍了从文本文件中删除一行的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文本文件中删除某行.这样做的最有效方法是什么?文件可能很大(超过一百万条记录).

更新:下面是我目前使用的代码,但我不确定它是否合适.

internal void DeleteMarkedEntries() {字符串 tempPath=Path.GetTempFileName();使用 (var reader = new StreamReader(logPath)) {使用 (var writer = new StreamWriter(File.OpenWrite(tempPath))) {整数计数器 = 0;而 (!reader.EndOfStream) {如果(!_deletedLines.Contains(计数器)){writer.WriteLine(reader.ReadLine());}++计数器;}}}if (File.Exists(tempPath)) {File.Delete(logPath);File.Move(tempPath, logPath);}}

解决方案

最直接的方法可能是最好的,将整个文件写到一个新文件中,写除你的行之外的所有行不想.

或者,打开文件进行随机访问.

阅读到要删除"该行的位置.跳过要删除的行,然后读取该字节数(包括 CR + LF - 如有必要),将该字节数写入已删除的行,将两个位置都按该字节数前进并重复直到文件结束.

希望这会有所帮助.

编辑 - 现在我可以看到你的代码了

if (!_deletedLines.Contains(counter)){writer.WriteLine(reader.ReadLine());}

行不通,如果它是您不想要的行,您仍然想阅读它只是不写.上面的代码既不会读也不会写.新文件将与旧文件完全相同.

你想要类似的东西

string line = reader.ReadLine();如果(!_deletedLines.Contains(计数器)){writer.WriteLine(line);}

I need to delete a certain line from a text file. What is the most efficient way of doing this? File can be potentially large(over million records).

UPDATE: below is the code I'm currently using, but I'm not sure if it is good.

internal void DeleteMarkedEntries() {
    string tempPath=Path.GetTempFileName();
    using (var reader = new StreamReader(logPath)) {
        using (var writer = new StreamWriter(File.OpenWrite(tempPath))) {
            int counter = 0;
            while (!reader.EndOfStream) {
                if (!_deletedLines.Contains(counter)) {
                    writer.WriteLine(reader.ReadLine());
                }
                ++counter;
            }
        }
    }
    if (File.Exists(tempPath)) {
        File.Delete(logPath);
        File.Move(tempPath, logPath);
    }
}

解决方案

The most straight forward way of doing this is probably the best, write the entire file out to a new file, writing all lines except the one(s) you don't want.

Alternatively, open the file for random access.

Read to the point where you want to "delete" the line. Skip past the line to delete, and read that number of bytes (including CR + LF - if necessary), write that number of bytes over the deleted line, advance both locations by that count of bytes and repeat until end of file.

Hope this helps.

EDIT - Now that I can see your code

if (!_deletedLines.Contains(counter)) 
{                            
    writer.WriteLine(reader.ReadLine());                        
}

Will not work, if its the line you don't want, you still want to read it, just not write it. The above code will neither read it or write it. The new file will be exactly the same as the old.

You want something like

string line = reader.ReadLine();
if (!_deletedLines.Contains(counter)) 
{                            
    writer.WriteLine(line);                        
}

这篇关于从文本文件中删除一行的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆