1. 程式人生 > >從一個目錄複製到另一個目錄

從一個目錄複製到另一個目錄

/// <summary>
/// 拷貝oldlab的檔案到newlab下面
/// </summary>
/// <param name="sourcePath">lab檔案所在目錄(@"~\labs\oldlab")</param>
/// <param name="savePath">儲存的目標目錄(@"~\labs\newlab")</param>
/// <returns>返回:true-拷貝成功;false:拷貝失敗</returns>
public bool CopyOldLabFilesToNewLab(string sourcePath, string savePath)
{
    if (!Directory.Exists(savePath))
    {
        Directory.CreateDirectory(savePath);
    }

    #region //拷貝labs資料夾到savePath下
    try
    {
        string[] labDirs = Directory.GetDirectories(sourcePath);//目錄
        string[] labFiles = Directory.GetFiles(sourcePath);//檔案
        if (labFiles.Length > 0)
        {
            for (int i = 0; i < labFiles.Length; i++)
            {
                if (Path.GetExtension(labFiles[i]) != ".lab")//排除.lab檔案
                {
                    File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" + Path.GetFileName(labFiles[i]), true);
                }
            }
        }
        if (labDirs.Length > 0)
        {
            for (int j = 0; j < labDirs.Length; j++)
            {
                Directory.GetDirectories(sourcePath + "\\" + Path.GetFileName(labDirs[j]));

                //遞迴呼叫
                CopyOldLabFilesToNewLab(sourcePath + "\\" + Path.GetFileName(labDirs[j]), savePath + "\\" + Path.GetFileName(labDirs[j]));
            }
        }
    }
    catch (Exception)
    {
        return false;
    }
    #endregion
    return true;
}