c# - 从 .txt 文件 C# 中删除特定单词
问题描述
所以我一直在开发一个控制台库存系统,它可以选择添加/删除东西并将其保存在 .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);
}
此外,在解决上述问题后。我忘了提到的是,例如,当我将数量为 100 的库存(文本文件)项目代码 AP01 添加到我的文本文件中时,它将具有以下内容:
AP01 100
现在我想要实现的是,在我输入我的 itemCode 以从文本文件中删除项目之后,我试图要求用户输入“数量”。例如,如果我将 itemCode 设置为 AP01(删除),它会要求我输入一个值,例如 25。
所以这
AP01 100
会变成这样
AP01 75
这是我得到答案后更新的代码:
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();
Console.WriteLine("Enter the amount that you'd like to remove: ");
string itemQuantity = Console.ReadLine();
var newLines = lines.Where(line => !line.Contains(itemCode, StringComparison.OrdinalIgnoreCase));
File.WriteAllLines(filePath, newLines);
解决方案
执行 aList<T>.Remove()
只会从列表中删除条目,而不一定是单词。这是假设文本文件的内容多于行中的项目代码。假设文本文件看起来像这样:
你好世界
是的,打招呼是多么美好的一天
再会
您可以编写以下代码来删除“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));
输出将是
再会
编辑
根据您的编辑,您可能希望创建一个模型来表示文本文件中的项目,如下所示:
public class Item
{
public Item(string input)
{
var splitInput = input.Split(' ');
Code = splitInput[0];
Qty = int.Parse(splitInput[1]);
}
public Item(string code, int qty)
{
Code = code;
Qty = qty;
}
public string Code { get; }
public int Qty { get; }
public override string ToString()
{
return $"{Code} {Qty}";
}
}
代码看起来像:
static void Main(string[] args)
{
string filePath = @"path\to\file.txt";
var lines = File.ReadAllLines(filePath).Select(line => new Item(line));
string itemCode = "AP01";
int qty = 25;
var newLines = lines
.Select(item => item.Code == itemCode ? new Item(item.Code, item.Qty - qty) : item)
.Where(item => item.Qty > 0)
.Select(item => item.ToString());
File.WriteAllLines(filePath, newLines);
}
这将减少数量,如果它们为 0 或更少,则将它们从文本文件中删除。