从.txt文件C#中删除特定单词

问题描述 投票:1回答:1

所以我一直在使用控制台清单系统,该系统可以选择添加/删除内容并将其保存为.txt文件。我设法将内容添加到.txt文件并保存,但是无法删除.txt文件中的特定单词。我在下面附加的代码应该从我打开的文本文件中删除保存在字符串中的单词。但是在运行代码并检查它是否存在之后,我发现它仍然存在。我是C#的新手,所以我对此并不了解,所以将不胜感激!

static void RemoveStock()
{
    Console.WriteLine("==============================");
    string filePath = @"C:\Users\Ibrah\OneDrive\Desktop\SDAM\Stock Management\Stock Management System\Intentory System\database\Stock.txt.txt";
    List<string> lines = new List<string>();
    lines = File.ReadAllLines(filePath).ToList();

    Console.WriteLine("Enter the item code you'd like to remove: ");
    string itemCode = Console.ReadLine();
    lines.Remove(itemCode);
    File.WriteAllLines(filePath, lines);

}
c# file
1个回答
0
投票

执行List<T>.Remove()只会从列表中删除条目,而不必删除单词。这是基于以下假设:文本文件中的行数超过了项目代码。假设文本文件看起来像这样:

Hello world

是的,打个招呼真是美好的一天

早安

比您可以编写以下代码来删除“ Hello”:

string filePath = @"path\to\file.txt";
var lines = File.ReadAllLines(filePath);
string itemCode = "Hello";
// If you don't want the replace to be case insensitive, do line.Replace(itemCode, string.Empty)
var newLines = lines.Select(line => Regex.Replace(line, itemCode, string.Empty, RegexOptions.IgnoreCase));
File.WriteAllLines(filePath, newLines);

输出将是:

世界

是,这是多么美好的一天

早安

如果您要删除包含您的商品代码的行,请将newLine替换为:

var newLines = lines.Where(line => !line.Contains(itemCode, StringComparison.OrdinalIgnoreCase));

哪个输出将是

早安

© www.soinside.com 2019 - 2024. All rights reserved.