替换部分文件名在C# [英] Replace part of a filename in C#

查看:133
本文介绍了替换部分文件名在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

家伙。

我有一个包含.pdf文件的文件夹。在大多数文件的名称中,我想用另一个字符串替换特定的字符串。此时我写了:

I have a folder with .pdf files. In the names of most files I want to replace specific string with another string. At this moment I wrote this:

  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;
    }

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

Here I extract all file names in List Box.

    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);
            }

        }

替换,但是东西出了问题。什么?

And here I want to do the replacing, but something gones wrong. What?

推荐答案

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

It sounds like you want to change the name of the file on disk. If so then you need to use the File.Move API vs. changing the actual string which is the file name.

另一个错误是替换调用本身。 .Net中的字符串是不可变的,因此所有变化的API(如 Replace )返回一个新的 string 与更改旧的地方。要查看更改,您需要将新值分配回变量

One other mistake you are making is the Replace call itself. A string in .Net is immutable and hence all of the mutating APIs like Replace return a new string vs. changing the old one in place. To see the change you need to assign the new value back to a variable

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

这篇关于替换部分文件名在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆