简体   繁体   中英

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. 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.

Ryan Rock ,345 ,Food ,$456.00 ,Pending ,4/2/2015 3:48:45 PM

Smith ,4567 ,Food ,$2.00 ,Pending ,4/2/2015 6:26:37 PM

Jerry ,444 ,Travel ,$22.00 ,Pending ,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)

or you can try to use a XMl / JSON type of formatting as your text file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM