Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to rename a file

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 88
    Comment on it

    We have two ways by which we can rename our file

    1.  Move method

    2. MoveTo method

    1. Move method

    Move method move a specified file to a new location.

    Syntax:

    public static void Move( string sourceFileName, string destinationFileName )

    It accepts the two parameters :

    1. sourceFileName is a String type which define the name of the file to move.

    2. destFileName is a String type which define the new path and name for the file.

    Add the following namespace in you C# code

    using System;

    using System.IO;

     

    C# Code

    static void Main(string[] args)
       {
           try
            {   
                 if (!File.Exists(@"D:\dta\SubFolder\f2.txt") && File.Exists(@"D:\dta\SubFolder\f1.txt"))
                  {
                       File.Move(@"D:\dta\SubFolder\f1.txt", @"D:\dta\SubFolder\f2.txt");
                 }
                   else 
                   {
                       Console.WriteLine("The file is already exists");
                  }	
            }
       catch(Exception e)
          {
               Console.WriteLine("TError!!!: {0}", e.ToString());
            }
      }

     

    2. MoveTo method

    MoveTo method also move a specified file to a new location.

    name.

    Syntax:

    public void MoveTo( string destFileName )

    It accepts only one parameter "destFileName" which is a String type which define the new path and name for a file.

    For example,

    c:\f1.txt can be moved to d:\public and renamed f2.txt.

    Add the following namespace in you C# code

    using System;

    using System.IO;

    C# Code

    public static void Main() 
        {
            try
               {
               FileInfo fileInfo = new FileInfo(@"D:\dta\SubFolder\f1.txt");
                 {
                    if (!File.Exists(@"D:\dta\SubFolder\f2.txt"))
                    {
                         fileInfo.MoveTo(@"D:\dta\SubFolder\f2.txt");
                    }
                  else
                     {
                           Console.WriteLine("The file is already exists");
                       }
                  }
              catch(Exception e)
               {
                    Console.WriteLine("Error!!!: {0}", e.ToString());
                 }
            }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: