使用C#中的Foreach循环浏览文件,并在.pdf之前删除破折号和三个额外的字符

问题描述 投票:-4回答:3

我在桌面目录中的文件中扫描了几百个。我需要遍历它们并更改文件名。文件必须保留其名称的前6个字符。破折号之后的所有内容(包括破折号)都需要删除。也需要文件扩展名(.pdf)。

文件名是这样的:

000001-067.pdf000034-003.pdf000078-123.pdf000009-011.pdf

我需要做的是删除文件名中的破折号和最后三个字符。因此结果将是:

000001.pdf000034.pdf000078.pdf000009.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
}
c# filenames
3个回答
1
投票

这是我的解决方法:

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
投票

我认为问题是f.Name仅返回文件的名称,而不是移动文件所需的完整路径。一个简单的主意是获取f.FullNamef.Name,因此一旦移动它们,就可以指定存档的原始路径,并将新目录路径与新文件合并名称(您已经重新定义)以移动它。


0
投票

它正在尝试重命名/移动当前目录中的文件,而不是最初扫描的目录中的文件。试试:

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));
}
© www.soinside.com 2019 - 2024. All rights reserved.