In this example of I will show how to rename all the files in a directory using asp.net. Sometimes you may have thousands of photos that require to rename or add extention at the end the file name. I have used very simple script to rename all the files in a folder with button click event.
First I have inserted a button in my default.aspx page and named that btnRename. In this example I want to add .gif extention with all the files in that folder as currently those files does not have any extention. For the onClick event of that button I have included the following script –
VB Code:
Protected Sub btnRename_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRename.Click Dim source As String Dim i As String = 0 'Folder to rename files source = Server.MapPath("~/test/") For Each fName As String In Directory.GetFiles(source) Dim dFile As String = String.Empty dFile = Path.GetFileName(fName) Dim dFilePath As String = String.Empty dFilePath = source + dFile Dim fi As New FileInfo(dFilePath) fi.MoveTo(source + dFile + ".gif") 'adding extention .gif with the actual file name Next i = Nothing End Sub
If you are using C# then make sure you include onClick event for the specified button –
protected void btnRename_Click(object sender, System.EventArgs e) { string source = null; string i = 0; //Folder to rename files source = Server.MapPath("~/test/"); foreach (string fName in Directory.GetFiles(source)) { string dFile = string.Empty; dFile = Path.GetFileName(fName); string dFilePath = string.Empty; dFilePath = source + dFile; FileInfo fi = new FileInfo(dFilePath); //adding extention .gif with the actual file name fi.MoveTo(source + dFile + ".gif"); } i = null; }