在 C# 中重命名文件并排除文件的扩展名

use*_*011 2 c# asp.net

FileInfo currentFile = new FileInfo("c:\\Blue_ 327 132.pdf"); 
string fileNameFromDB = "c:\\Blue 327 _132.pdf"; 
string newFileName = fileNameFromDB + currentFile.Extension; 
currentFile.MoveTo(newFileName); 
Run Code Online (Sandbox Code Playgroud)

我需要用新的 filenamefromDB 重命名它

C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\Orange_  325_  131.pdf
Run Code Online (Sandbox Code Playgroud)

由于我使用的是 system.io.path 但文件存在于 C;\Uploads\..

如果我对多个文件进行循环并且每次目录路径都不同怎么办?

ale*_*lex 5

重命名单个文件

FileInfo currentFile = new FileInfo("c:\\Blue_ 327 132.pdf");
currentFile.MoveTo(currentFile.Directory.FullName + "\\" + newName);
Run Code Online (Sandbox Code Playgroud)

其中 newName 是没有路径的新名称。例如,“new.pdf”

如果您需要保留旧的文件扩展名

FileInfo currentFile = new FileInfo("c:\\Blue_ 327 132.pdf");
currentFile.MoveTo(currentFile.Directory.FullName + "\\" + newName + currentFile.Extension);
Run Code Online (Sandbox Code Playgroud)

重命名多个文件

DirectoryInfo d = new DirectoryInfo("c:\\temp\\"); 
FileInfo[] infos = d.GetFiles();
foreach(FileInfo f in infos)
{
    File.Move(f.FullName, f.FullName.ToString().Replace("abc_","");
}
Run Code Online (Sandbox Code Playgroud)