How do I move a file to another location?

Category: System.IO, viewed: 1K time(s).
using System;
using System.IO;

namespace Kodecsharp.Example.System.IO
{
	class FileMoveDemo
	{
        public static void Main(string[] args) {
            string src = @"c:\users\me\demo.txt";
            string dest = @"c:\users\me\demo.txt.bak";

            //
            // This example shows how to move a file. We use the File's
            // class Move() static method. It takes two parameters, the
            // source file name and the destination file name.
            //
            // We add some file checking condition to check whether to
            // source file exists and the target file doesn't exists
            // before we move the file.
            //
            if (File.Exists(src) && !File.Exists(dest)) {
                File.Move(src, dest);
            }

            //
            // We can also use the FileInfo.MoveTo() method to move a 
            // file.
            //
            if (File.Exists(dest) && !File.Exists(src)) {
                FileInfo fi = new FileInfo(dest);
                fi.MoveTo(src);
            }
        }
	}
}
Powered by Disqus