尝试更新文本文件

时间:2016-01-27 08:30:11

标签: c#

点击“更新”按钮时,我试图替换.txt文件中的某一行

这是我的程序的样子 http://i.imgur.com/HKu4bGo.png

这是我目前的代码

        string[] arrLine = File.ReadAllLines("Z:/Daniel/SortedAccounts.txt");
        arrLine[accountComboBox.SelectedIndex] = "#1#" + firstNameInfoBox.Text + "#2#" + lastNameInfoBox.Text + "#3#" + emailInfoBox.Text + "#4#" + phoneNumberInfoBox.Text + "#5#EMAIL#6#";
        File.WriteAllLines("Z:/Daniel/SortedAccounts.txt", arrLine);

这就是SortedAccounts.txt

中的内容
  

#1#Bob#2#Smith#3#Bob@Smith.com#4#5551234567#5#EMAIL#6#   #1#Dan#2#Lastyy#3#Daniel@Lastyy.com#4#5551234567#5#EMAIL#6#

ComboBox的顺序为Txt文件。

因此,我获得与ComboBox中所选项目相同的索引。然后我想删除该行,然后使用更新的信息添加一个相同txt文件的新行。

我的代码由于某种原因不能这样做而我无法弄清楚

1 个答案:

答案 0 :(得分:1)

尝试使用List轻松删除某个索引处的条目。不要忘记在更新文件时重新加载组合框数据源以避免索引不匹配等。

List<string> arrLine = File.ReadAllLines("Z:/Daniel/SortedAccounts.txt").ToList();
arrLine.RemoveAt(accountComboBox.SelectedIndex);
string newLine = "#1#" + firstNameInfoBox.Text + "#2#" + lastNameInfoBox.Text + "#3#" + emailInfoBox.Text + "#4#" + phoneNumberInfoBox.Text + "#5#EMAIL#6#";
arrLine.Add(newLine);
File.WriteAllLines("Z:/Daniel/SortedAccounts.txt", arrLine);