如何重命名文件中的选定文本?

时间:2014-07-13 23:17:53

标签: c# listbox rename

我制作了一个程序,您可以在文本框中添加文本,然后将其添加到列表框中。现在要在下次应用程序启动时实际保存它,我决定将它存储到一些text.ini文件中。

现在,下次应用程序启动时(表单加载),使用StreamReader读取该文件中的所有文本并将其显示在列表框中。

我决定实施编辑功能(从列表框中选择项目 - >右键单击 - >编辑),然后重命名该文件(以防错误拼写)。

我的问题是:

如果我在列表框中有1个项目并将其重命名,那么它的效果非常好。

但是如果我在列表框中有2个或更多项目但决定只重命名1,它会从文件中删除所有文本并仅重命名所选项目。

这是我的代码:

string itemName = (string)lBoxRadioLinks.SelectedItem;
var renameFile = Interaction.InputBox("Enter a new name for the file:", "Rename File", itemName);

// Gets the selected item full name
var url = lBoxRadioLinks.GetItemText(lBoxRadioLinks.SelectedIndex);
string lineToRename = url.ToString();

// Selected file
//MessageBox.Show(lineToRename);

// ACTUALLY rename the text
string[] lines = File.ReadAllLines("IO/sites.ini");
List<string> list = new List<string>();

foreach (string line in lines)
{
    if (line != lineToRename)
        list.Add(line);
}

// Have to convert the string into array for an actual rename
string[] arr = new string[] { renameFile };

// Visually rename the file (display in listbox asap)
lBoxRadioLinks.DataSource = arr;

// Renames the file
File.WriteAllLines("IO/sites.ini", arr);  

显然方法&#34; WriteAllLines&#34;将重命名文件中的整个文本,但我不想要它。

如何在不影响文件中其他行的情况下重命名某行的文本?

1 个答案:

答案 0 :(得分:0)

我真的不知道你在问什么,但我会尽我所能。

如果我们在同意您替换文本文件中的某些文字时我们彼此了解,并且如果您真的可以将整个内容加载到内存中,那么你也可以使用string.Replace方法。

Dictionary<string, string> changesToMake = ...;
var contents = File.ReadAllText(filename);

foreach(var change in changesToMake)
{
    contents = contents.Replace(change.Key, change.Value);
}

File.WriteAllText(filename, contents);

至于您在ListBox中使用多个项目所遇到的问题,您只需引用SelectedItemSelectedIndex属性,因此不应更改任何内容除了那些...文件以外的任何地方?我还不确定ListBox中的内容。如果您想一次更改多个,则应使用每个属性的复数形式来访问所有选定的项目,而不仅仅是第一个。

相关问题