본문 바로가기

언어/C#

directory관련

 

//..디렉토리 생성 ( 존재하지 않으면 생성 )
public void CreateDirectory(string path)
{
    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
}

public void CreateDirectory(DirectoryInfo dInfo)
{
    if (!dInfo.Exists) dInfo.Create();
}


//..디렉토리 사이즈
public long DirectorySize(string path, bool includeSubDir)
{
    DirectoryInfo dInfo = new DirectoryInfo(path);
    return DirectorySize(dInfo, includeSubDir);
}

//..디렉토리 사이즈(Byte)
//..KByte : / 1024
//..MByte : / ( 1024 * 1024 )
public long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
{
    long totalSize = dInfo.EnumerateFiles().Sum(file => file.Length);
    if (includeSubDir) totalSize += dInfo.EnumerateDirectories().Sum(dir => DirectorySize(dir, true));
    return totalSize;
}

//..디렉토리 Copy
public void CopyDirectory(string sourcePath, string destinationPath)
{
    DirectoryInfo source = new DirectoryInfo(sourcePath);
    DirectoryInfo destination = new DirectoryInfo(destinationPath);
    CopyDirectory(source, destination);
}

//..디렉토리 Copy
public void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
    CreateDirectory(destination);
    // Copy all files.
    FileInfo[] files = source.GetFiles();
    foreach (FileInfo file in files)
    {
        file.CopyTo(Path.Combine(destination.FullName,file.Name));
    }
    // Process subdirectories.
    DirectoryInfo[] dirs = source.GetDirectories();
    foreach (DirectoryInfo dir in dirs)
    {
        // Get destination directory.
        string destinationDir = Path.Combine(destination.FullName, dir.Name);
        CopyDirectory(dir, new DirectoryInfo(destinationDir)); // Call CopyDirectory() recursively.
    }
}