繁体   English   中英

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

[英]Renaming a file in C# and excluding the extension of the file

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

我需要用 new filenamefromDB 重命名它

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

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

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

重命名单个文件

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

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

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

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

重命名多个文件

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

这是 function System.IO.File.Move的解释,将文件“移动”到新名称。

System.IO.File.Move(OldNameFullPath,NewNameFullPath);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM