How do I copy a file into another file?

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

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

            //
            // File.Copy() will copy the defined source file to the
            // defined target file. The third parameter is a boolean
            // value that tell whether to overwrite the target file
            // or not.
            //    
            if (File.Exists(source)) {
                File.Copy(source, target, true);
            }

            //
            // We can also use the FileInfo's CopyTo() instance method
            // to copy a file. It also provided an overload that allows
            // us to overwrite the existing target file.
            //
            if (File.Exists(source)) {
                FileInfo fi = new FileInfo(source);
                fi.CopyTo(target, true);
            }
        }
    }
}
Powered by Disqus