Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace part of a filename in C#

I have a folder with .pdf files. In the names of most files I want to replace specific string with another string.

Here's what I've written.

  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 is going wrong. What?

like image 272
vladislavn Avatar asked May 07 '12 19:05

vladislavn


3 Answers

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.

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);
like image 187
JaredPar Avatar answered Nov 06 '22 13:11

JaredPar


f.Name is a read-only property. f.Name.Replace(..) simply returns a new string with the filename you want, but never actually changes the file.
I suggest something along the following, though I haven't tested it:

File.Move(f.Name, f.Name.Replace(strReplace, strWith));
like image 20
Charles Josephs Avatar answered Nov 06 '22 11:11

Charles Josephs


Replace return another string, it doesn't change the original string.
So you need to write

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

of course this doesn't change the name of the file on disk.
If that was your intention then you should look at

File.Move(f.Name, newName);

also keep in mind that File.Move will fail with an exception if the destination file exists.

See here for an example

like image 1
Steve Avatar answered Nov 06 '22 12:11

Steve