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
    • 191
    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

    1. static void Main(string[] args)
    2. {
    3. try
    4. {
    5. if (!File.Exists(@"D:\dta\SubFolder\f2.txt") && File.Exists(@"D:\dta\SubFolder\f1.txt"))
    6. {
    7. File.Move(@"D:\dta\SubFolder\f1.txt", @"D:\dta\SubFolder\f2.txt");
    8. }
    9. else
    10. {
    11. Console.WriteLine("The file is already exists");
    12. }    
    13. }
    14. catch(Exception e)
    15. {
    16. Console.WriteLine("TError!!!: {0}", e.ToString());
    17. }
    18. }

     

    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

    1. public static void Main()
    2. {
    3. try
    4. {
    5. FileInfo fileInfo = new FileInfo(@"D:\dta\SubFolder\f1.txt");
    6. {
    7. if (!File.Exists(@"D:\dta\SubFolder\f2.txt"))
    8. {
    9. fileInfo.MoveTo(@"D:\dta\SubFolder\f2.txt");
    10. }
    11. else
    12. {
    13. Console.WriteLine("The file is already exists");
    14. }
    15. }
    16. catch(Exception e)
    17. {
    18. Console.WriteLine("Error!!!: {0}", e.ToString());
    19. }
    20. }
    21.  

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: