Welcome to W3Courses
 Like Us on Facebook

Rename a File on the Disk or Local File System using C#

The following code will rename a file called temp.txt to tempnew.txt

using System.IO;

try
{
      FileInfo TheFile = new FileInfo("C:\\" + "temp.txt");
      if (TheFile.Exists)
      {
             File.Move("C:\\" + "temp.txt", "C:\\" + "tempnew.txt");
      }
      else
      {
            throw new FileNotFoundException();
      }
}

catch (FileNotFoundException ex)
{
      lblDisplay.Text += ex.Message;
}

catch (Exception ex)
{
      lblDisplay.Text += ex.Message;
}

Share