且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C#中的文本文件中删除特定行(查看详细信息)

更新时间:2023-11-18 19:45:40

逐行读取文件并逐行将结果写入不同的文件中,跳过所需的行。使用这两个类:

https://msdn.microsoft.com/en-us/library/system.io.streamreader%28v=vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en -us / library / system.io.streamwriter%28v = vs.110%29.aspx [ ^ ]。



输出文件,使用临时文件名: https:// msdn.microsoft.com/en-us/library/system.io.path.gettempfilename%28v=vs.110%29.aspx [ ^ ]。



它完成后,将临时文件重命名为原始文件,如果这是你需要的。具体方法如下: https:// msdn。 microsoft.com/en-us/library/system.io.file.move%28v=vs.110%29.aspx [ ^ ]。



不要忘记关闭所有流,否则文件将无法访问。***的方法是调用 IDisposable.Dispose 读者和作者的方法,反过来,***的方法是使用使用 声明(不要与使用 指令混淆):

https://msdn.microsoft.com/en-us/library/ yh598w02.aspx [ ^ ],

https:// msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx [ ^ ]。



这是一种非常通用的方法,适用于任何大小的文件。



现在,对于较小的文件,这是轻量级方法:读取所有行一旦到内存,处理行以忽略不需要的行,将所有行写入文件:

https://msdn.microsoft.com/en-us/library/system.io.file.readalllines%28v=vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/system.io.file.writealllines%28v=vs.110%29.aspx [ ^ ]。



-SA
Read the file line by line and write the result in a different file line by line, skipping the required lines. Use these two classes:
https://msdn.microsoft.com/en-us/library/system.io.streamreader%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.io.streamwriter%28v=vs.110%29.aspx[^].

For output file, use temporary file name: https://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename%28v=vs.110%29.aspx[^].

When it is done, rename temporary file to the original file, if this is what you need. This is how: https://msdn.microsoft.com/en-us/library/system.io.file.move%28v=vs.110%29.aspx[^].

Don't forget to close all streams, otherwise the files will remain inaccessible. The best way to do it is to call IDisposable.Dispose methods of the reader and the writer, and, in turn, the best way to do it is to use using statement (not to be mixed up with using directive):
https://msdn.microsoft.com/en-us/library/yh598w02.aspx[^],
https://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx[^].

This is a very universal approach which can work for the files of any size.

Now, this is light-weight approach for smaller files: read all lines at once to memory, process the lines to ignore unwanted lines, write all lines to the file:
https://msdn.microsoft.com/en-us/library/system.io.file.readalllines%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.io.file.writealllines%28v=vs.110%29.aspx[^].

—SA