C#中如何替换文件名的一部分

5
我有一个包含.pdf文件的文件夹。我想在大多数文件名中替换特定的字符串为另一个字符串。
以下是我写的代码。
  private void btnGetFiles_Click(object sender, EventArgs e)
    {
        string dir = tbGetFIles.Text;
        List<string> FileNames = new List<string>();

        DirectoryInfo DirInfo = new DirectoryInfo(dir);

        foreach (FileInfo File in DirInfo.GetFiles())
        {
            FileNames.Add(File.Name);       
        }

        lbFileNames.DataSource = FileNames;
    }

在这里,我提取列表框中的所有文件名。

    private void btnReplace_Click(object sender, EventArgs e)
    {
        string strReplace = tbReplace.Text; // The existing string
        string strWith = tbWith.Text; // The new string

        string dir = tbGetFIles.Text;
        DirectoryInfo DirInfo = new DirectoryInfo(dir);
        FileInfo[] names = DirInfo.GetFiles();


        foreach (FileInfo f in names)
        {
            if(f.Name.Contains(strReplace))
            {
                f.Name.Replace(strReplace, strWith);
            }

        }

我想在这里进行替换,但是出了些问题。什么原因?


但是出了些问题。什么问题呢?你应该告诉我们出了什么问题(你遇到了什么问题),然后我们可以帮助你找出如何解决它。你还没有这样做。请编辑你的问题,以便实际上有一个可以回答的问题。谢谢 :) - Ken White
"Replace不是替换。Replace返回替换后的字符串。" - GSerg
5个回答

7

看来您想要更改磁盘上文件的名称。如果是这样,那么您需要使用File.Move API而不是更改文件名的实际字符串。

您还犯了另一个错误,就是Replace调用本身。在.NET中,string是不可变的,因此所有可变API(如Replace)都会返回一个新的string,而不是直接在原来的字符串上进行更改。要看到更改,您需要将新值重新分配给一个变量。

string newName = f.Name.Replace(strReplace, strWith);
File.Move(f.Name, newName);

2

f.Name是只读属性。f.Name.Replace(..)仅仅返回一个新的字符串,包含你想要的文件名,但并不会实际改变文件。
我建议使用以下代码,虽然我没有测试过:

File.Move(f.Name, f.Name.Replace(strReplace, strWith));

1
它可以工作:File.Move(dir + @"" + f.Name, dir + @"" + f.Name.Replace(strReplace, strWith)); - vladislavn
很好的发现。更好的做法可能是使用Path.Combine。 - Charles Josephs

1

替换返回另一个字符串,它不会改变原始字符串。
所以你需要编写

string newName = f.Name.Replace(strReplace, strWith); 

当然,这并不会改变磁盘上文件的名称。
如果您的意图是更改文件名,则应查看

File.Move(f.Name, newName);

请注意,如果目标文件已存在,则File.Move将失败并引发异常。

点击此处查看示例


0
乍一看,似乎您没有将替换后的字符串重新分配给f.Name变量。请尝试这样做:
string NewFileName = f.Name.Replace(strReplace, strWith);
File.Copy(f.Name, NewFileName);
File.Delete(f.Name);

你说得对,谢谢指出。我已经修改了我的回复。 - Adolfo Perez

0
当你调用 string.Replace 时,它不会改变你现有的字符串。相反,它会返回一个新的字符串。
你需要将你的代码更改为类似这样的形式:
if(f.Name.Contains(strReplace)) 
{ 
    string newFileName = f.Name.Replace(strReplace, strWith); 
    //and work here with your new string
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接