Replace part of a filename in C#

c#-4.0, string, visual-studio-2010

Solution

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

Problem

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?

Original source

Related problems