I have several hundred scanned in files within a Desktop directory. I need to loop thru them and change the file names. The files must retain the first 6 characters of their name. Everything after and including the dash needs to be removed. The file extension (.pdf) is needed too.
The file names are like this:
000001-067.pdf 000034-003.pdf 000078-123.pdf 000009-011.pdf
What I need to do is remove the the dash and final three characters in file name. So the results will be:
000001.pdf 000034.pdf 000078.pdf 000009.pdf
I wrote the following code but it throws an error on File.Move. Any ideas how to fix it?
DirectoryInfo d = new DirectoryInfo(@"C:\Users\BrewMaster\Desktop\ScannedFilesToProcess\");
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
string fileName = f.Name;
int indexOfDash = fileName.LastIndexOf('-'); // find the position of -
int indexOfPeriod = fileName.LastIndexOf('.'); // find the position of .
// find remove the text between - and .
string newFileName = fileName.Remove(indexOfDash, indexOfPeriod - indexOfDash);
//File.Move(f.FullName, f.FullName.Replace("-", "")); //This only removes the dash. The 3 characters after it remain
File.Move(f.Name, newFileName); //This throws and error. System.IO.FileNotFoundException ' Could not find file C:\Users\BrewMaster\source\repos\ChangeFileName\bin\Debug\000001-067.pdf
}
f.Namedoes not include the full path. TryDirectory.GetFiles()instead