I have a simple foreach here where I am have got the folder location using the folderBrowserDialog tool and am now trying to go through each one of the files and replace certain characters within the file name.
I am getting an error which says it cannot find the file when it gets to this part of the code File.Move(_FileName, _NewFileName);
Can anyone shed any light on this? Would be much appreciated.
Thanks
foreach (FileInfo Files in Folder.GetFiles())
{
_FileName = Files.Name;
_NewFileName = _FileName.Replace(" ", "-").Replace(",", "-");
File.Move(_FileName, _NewFileName);
File.Delete(_FileName);
}
You need to use
Files.FullNamenotFiles.NameFullNameincludes the full path (i.e.C:\test\foo.txt) which is needed byFile.Move()andFile.Delete()whileNameis just the file name itself (i.e.foo.txt).Edit:
@crashmstr is correct you should not do a string replace on the full path. All in all I’d probably do it this way:
Also keep in mind
File.Delete()is not needed here, since the original file won’t be there anymore after you move it.