Copy, Move, or Delete a File or Directory - CSharp File IO

CSharp examples for File IO:File

Description

Copy, Move, or Delete a File or Directory

Demo Code


using System;// w  ww .j a  v  a  2 s. c  o m
using System.IO;

    static class MainClass
    {
        static void Main(string[] args)
        {
            DirectoryInfo sourceDir = new DirectoryInfo("c:/source/");
            DirectoryInfo destinationDir = new DirectoryInfo("c:/target/");

            CopyDirectory(sourceDir, destinationDir);

        }

        static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
        {
            if (!destination.Exists)
            {
                destination.Create();
            }

            // Copy all files.
            foreach (FileInfo file in source.EnumerateFiles())
            {
                file.CopyTo(Path.Combine(destination.FullName, file.Name));
            }

            // Process subdirectories.
            foreach (DirectoryInfo dir in source.EnumerateDirectories())
            {
                string destinationDir = Path.Combine(destination.FullName, dir.Name);
                CopyDirectory(dir, new DirectoryInfo(destinationDir));
            }
        }
    }

Result


Related Tutorials