Используйте цикл Foreach в C # для циклического перемещения по файлам и удаления дефиса плюс три дополнительных символа перед .pdf - PullRequest
0 голосов
/ 04 октября 2019

У меня есть несколько сотен отсканированных файлов в каталоге Desktop. Мне нужно пройти через них и изменить имена файлов. Файлы должны сохранять первые 6 символов своего имени. Все после и в том числе черту нужно убрать. Также необходимо расширение файла (.pdf).

Имена файлов выглядят так:

000001-067.pdf
000034-003.pdf
000078-123.pdf
000009-011.pdf

Что мне нужно сделать, это удалить тире и последние три символа в имени файла,Таким образом, результаты будут такими:

000001.pdf
000034.pdf
000078.pdf
000009.pdf

Я написал следующий код, но он выдает ошибку File.Move. Есть идеи как это исправить?

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
}

Ответы [ 3 ]

1 голос
/ 04 октября 2019

Вот мое решение:

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(f.Name, newFileName));     
}
0 голосов
/ 04 октября 2019

Он пытается переименовать / переместить файл в текущем каталоге, а не в том каталоге, который вы изначально сканировали. Попробуйте:

String path = @"C:\Users\BrewMaster\Desktop\ScannedFilesToProcess\";
DirectoryInfo d = new DirectoryInfo(path);
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(Path.Combine(path, f.Name), Path.Combine(path, newFileName));
}
0 голосов
/ 04 октября 2019

Я думаю, проблема в том, что f.Name возвращает только имя файла, а не полный путь, необходимый для его перемещения. Легкой идеей было бы получить f.FullName и f.Name , поэтому после его перемещения вы указываете исходный путь к архиву, а они объединяют новый путь к каталогу. с новым именем файла (которое вы уже переопределили), чтобы переместить его.

...