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

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

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

相关问题

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

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

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

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

据我所知,没有通用的delete-a-line-from-file函数。

如果文件不是很大,那么执行此操作的一种方法是将所有行加载到数组中:

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

您实际上可以使用C#generics来实现这一点:

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

没有火箭scien代码需要。希望这个简单和简短的代码将有所帮助 。

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

或者使用它

 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. 阅读并记住每一行

  2. 确定你想要摆脱的那个

  3. 算那一个

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

你是在Unix操作系统上吗?

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

这可以分三步完成:

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

什么? 使用文件打开,搜索位置然后使用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