Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a file in C# and excluding the extension of the file

Tags:

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); 

I need rename it with new filenamefromDB

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

Since I'm using system.io.path but the files are present under C;\Uploads\..

What if I have do looping for more than one files and directory path varies every time?

like image 509
user2271011 Avatar asked Sep 18 '25 00:09

user2271011


1 Answers

To rename a single file

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

where newName is your new name without path. For example, "new.pdf"

If you need to keep old file extension

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

To rename multiple files

DirectoryInfo d = new DirectoryInfo("c:\\temp\\"); 
FileInfo[] infos = d.GetFiles();
foreach(FileInfo f in infos)
{
    File.Move(f.FullName, f.FullName.ToString().Replace("abc_","");
}
like image 138
user2316116 Avatar answered Sep 20 '25 14:09

user2316116