查找并替换字符串中的特定单词

时间:2013-01-09 21:03:46

标签: c#

我想写一些c#代码,我在字符串中找到一个特定的单词,并从字符串中删除它而不删除整个字符串。

我尝试了这个,但它不起作用:

if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    // Read the files
    for (int i = 0; i < openFile.FileNames.Count(); i++ )
    {
        if (openFile.FileNames[i].Contains("Unknown Album"))
        {
            openFile.FileNames[i] = 
                openFile.FileNames[i].Replace("Unknown Album", string.Empty);
        }
    }
}

2 个答案:

答案 0 :(得分:8)

.FileNames类的OpenFileDialog属性只读。您必须将值存储在临时字符串中。

http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filenames.aspx

答案 1 :(得分:0)

if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    // Read the files
    for (int i = 0; i < openFile.FileNames.Count; i++ )
    {
        var file = openFile.FileNames[i];
        if (file.Contains("Unknown Album") && file  != "Unknown Album")
        {
            openFile.FileNames[i] = file.Replace("Unknown Album", string.Empty);
        }
    }
}