[英]How can I delete a line from List created from .txt file?
I need to delete a line from a List created from a .txt file. 我需要从.txt文件创建的列表中删除一行。
I have already made my list to be opened from a .txt file, I can see the list, I can add new client, and this client is being saved into the same .txt file, so next time I open it - I can see the "updated list". 我已经创建了要从.txt文件打开的列表,可以看到该列表,可以添加新客户端,并且此客户端将保存到相同的.txt文件中,因此下次我打开它-可以看到“更新列表”。
public static void ShowClientList()
{
string file =File.ReadAllText(@"C:\Users\Adminl\Documents\clients.txt");
Console.WriteLine(file);
Console.WriteLine();
}
public static void AddClient()
{
Console.WriteLine("Civ");
string civility = Console.ReadLine();
Console.WriteLine("Name");
string name = Console.ReadLine();
Console.WriteLine("Surname");
string surname = Console.ReadLine();
Console.WriteLine("Age");
string age = Console.ReadLine();
Console.WriteLine("Telephone No");
string telephone = Console.ReadLine();
string appendText = civility +','+" "+ name + ',' + " " + surname + ',' + " " + age + ',' + " " + telephone + Environment.NewLine; // This text is always added, making the file longer over time if its not deleted
string path = @"C:\Users\Adminl\Documents\clients.txt"; // FILE that either exist or no
File.AppendAllText(path, appendText);
}
What I mean I have a .txt file with clients (Mr, John, Smith, 25, 777-00-666) and I would like to either delete this client from a list or delete\\update one of the parameters (for ex. telephone number, the last one). 我的意思是我有一个带有客户端的.txt文件(Mr,John,Smith,25、777-00-666先生),我想从列表中删除此客户端或删除\\ update其中一个参数(例如电话号码,最后一个)。 Thank you for the help!
感谢您的帮助!
我认为您最好将此文件反序列化为包含这些属性的对象列表,然后可以进行修改,最后可以再次将其持久化。
This is kind of tedious if you're just using a text file. 如果您仅使用文本文件,这将很繁琐。 But for the sake of the question:
但是为了这个问题:
You can use a StringBuilder
to read all the contents from a file, do a split on commas (based on your format of (Mr, John, Smith, 25, 777-00-666)
and skip that line when appending to the StringBuilder, and re-write the file. 您可以使用
StringBuilder
读取文件中的所有内容,并以逗号分隔(根据您的格式(Mr, John, Smith, 25, 777-00-666)
并在追加到StringBuilder时跳过该行,并重新写入文件。
public static RemoveClient(string firstName, string lastName)
{
StringBuilder builder = new StringBuilder();
foreach(var line in File.ReadAllLines(@"C:\Users\Adminl\Documents\clients.txt")
{
var split = line.Split(',', StringSplitOptions.RemoveEmptyEntries);
if(split.Count < 3 || split[1] != firstName || split[2] != lastName) //|| any other comparisons you'd like to do
builder.AppendLine(line);
}
using(var writer = new StreamWriter(@"C:\Users\Adminl\Documents\clients.txt"))
{
writer.Write(builder.ToString());
writer.Flush();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.