Safely copies file, creating all necessary directories and overwriting destination. - CSharp File IO

CSharp examples for File IO:Directory

Description

Safely copies file, creating all necessary directories and overwriting destination.

Demo Code


using System.IO;/*  www. j  a v  a  2  s. c o m*/

public class Main{
        /// <summary>
      /// Safely copies file, creating all necessary directories and overwriting destination.
      /// </summary>
      public static void CopyFile(string sourceFile, string destFile)
      {
         string destDir = Path.GetDirectoryName(destFile);
         if (!Directory.Exists(destDir))
            Directory.CreateDirectory(destDir);

         if (File.Exists(destFile))
         {
            FileInfo fi = new FileInfo(destFile);
            fi.Attributes = FileAttributes.Normal;
         }

         File.Copy(sourceFile, destFile, true);
      }
}

Related Tutorials