C# 删除第 i 行文本文件,如果它与特定术语不同 [英] C# Delete line i text file if it is different than specific term

查看:29
本文介绍了C# 删除第 i 行文本文件,如果它与特定术语不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编辑一个文本文件并将内容从一个值更改为另一个值.到目前为止一切正常,但是在删除该文件中的一行时,我已经走到了尽头.我想要一个函数来读取具有类似内容的文件,如下所示...

I am editing a textfile and changing content from one value to another. Everything works fine so far but I have reached a dead end when it comes to deleting a line i that file. I want a function that reads a file with similar content as below...

彼得的名字

长度 185

名字苏珊

长度

哈利的名字

长度 177

并删除所有带有单词 Length NOT 后跟任何内容的行并给出结果

and removes all lines with the word Length NOT followed by anything and gives the result

彼得的名字

长度 185

名字苏珊

哈利的名字

长度 177

我用过代码

System.IO.File.WriteAllLines(
   strLabelExportTotal,
   File.ReadAllLines(strLabelExportPreLenAdjust)
      .Select(1 => 1 == "LENGTH " ? "LENGTH 0" : 1));

设置,如果单词 Length 之后的值丢失,则应将值设为 0.但现在我希望该行消失...

to set that if a value after the word Length is missing it should ad the value 0. But now I want the line to disappear...

推荐答案

您可以使用以下步骤:

  1. 将所有文本读取为字符串
  2. 将行拆分为字符串:\n as splitter
  3. 删除不需要的字符串/行 LENGTH
  4. 合并剩下的列表并写入文件
  1. Read all text as string
  2. Split lines into strings: \n as splitter
  3. Remove unwanted string/line LENGTH
  4. Combine the remaining list and write the file

代码:

string fileText = File.ReadAllText(path);            
var list = fileText.Split('\n').ToList();
list.Remove("LENGTH");
File.WriteAllLines(path, list);

var list = File.ReadAllLines(path).ToList();
list.Remove("LENGTH");
File.WriteAllLines(path, list);

这篇关于C# 删除第 i 行文本文件,如果它与特定术语不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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