Sponsored Ad

Tuesday, March 15, 2011

How to Move a File from one Directory to another Directory using C#

C# provide number of inbuilt functions for file operation. One important function is to move a file from one folder to another folder. There is two ways you can transfer a file

File.Move – use this method to directly transfer files
fobj.MoveTo - use this method in fileinfo object and move file.

image

using System;
using System.IO;
namespace MyApp
{
    class file_move_class
    {
        public static void Main(string[] args)
            {
            string source_file = @"d:\source\test.txt";
            string target_file = @"d:\target\test.txt";

            //Method 1
            if (File.Exists(source_file) && !File.Exists(target_file))
            {
                File.Move(source_file, target_file);
                Console.WriteLine("File Moved.");
            }

            //Method 2
            if (File.Exists(target_file) && !File.Exists(source_file))
            {
                FileInfo fobj = new FileInfo(target_file);
                fobj.MoveTo(source_file);
               // Console.WriteLine("File Moved.");
            }

            Console.Read();
        }
    }
}

No comments:

Post a Comment

Sponsored Ad

Development Updates