[英]C# Editing a text file
I have a single text file that I am trying to edit. 我有一个要编辑的文本文件。 Basically the text file holds data for a request in a business.
基本上,文本文件保存企业中的请求数据。 So it'll store the name, employee ID, request type, request total, request status, and the date and time in that order.
因此,它将按该顺序存储名称,员工ID,请求类型,请求总数,请求状态以及日期和时间。 I have to be able to edit the total amount for a selected line.
我必须能够编辑所选行的总金额。 I'm using a list view to be able to select the item.
我正在使用列表视图来选择项目。 So for example I have to take Smith's request, and edit the $2.00 and change it to let's say $4.00.
因此,例如,我必须接受Smith的请求,并编辑$ 2.00,然后将其更改为$ 4.00。
Ryan Rock ,345 ,Food ,$456.00 ,Pending ,4/2/2015 3:48:45 PM
Ryan Rock,345,食品,$ 456.00,待定,4/2/2015 3:48:45 PM
Smith ,4567 ,Food ,$2.00 ,Pending ,4/2/2015 6:26:37 PM
史密斯,4567,食品,$ 2.00,待定,4/2/2015 6:26:37 PM
Jerry ,444 ,Travel ,$22.00 ,Pending ,4/2/2015 6:26:47 PM
Jerry,444,旅行,$ 22.00,待定,4/2/2015 6:26:47 PM
private void btnModify_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView1.Items)
if (item.Selected)
{
string selected = item.Text.ToString();
string str;
double total;
bool totalCheck = double.TryParse(txtTotal.Text, out total);
if (totalCheck)
{
var lines = File.ReadAllLines("../../textFile/ExpenseReportingData.txt");
lines[3] = "7";
File.WriteAllLines("../../textFile/ExpenseReportingData.txt", lines);
}
else
{
MessageBox.Show("Please Enter A Valid Ammount", "Error");
}
}
}
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks.
谢谢。
to edit a value on a specific line u could do something like this : 编辑特定行上的值,您可以执行以下操作:
for (int i = 0; i < lines.Length; i++)
{
string[] lineData = lines[i].Split(',');//split the line into an array ["Smith" ,"4567" ,"Food" ,"$2.00" ,"Pending" ,"4/2/2015 6:26:37 PM"]
if (lineData[0] == "Smith")//0 is the index of the client name
{
lineData[3] = "$4.00";//modifie the value
lines[i] = String.Join(",", lineData);
File.WriteAllLines("../../textFile/ExpenseReportingData.txt", lines);
}
}
but I wouldn't recommend it , you should use a database to hold your data and each client has to have an unique id (many clients can have the same name this would create issues) 但我不推荐这样做,您应该使用数据库来保存数据,并且每个客户端都必须具有唯一的ID(许多客户端可以使用相同的名称,否则会产生问题)
or you can try to use a XMl / JSON type of formatting as your text file 或者您可以尝试使用XMl / JSON格式的格式作为文本文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.