'C# 폴더 존재 확인 및 폴더 생성'에 해당되는 글 1건

728x90

C# 에서 User Documnets 폴더 밑에다가 특정 폴더를 만들고 싶은 경우가 있다.

이때 간단하게 폴더를 생성하는 코드다.


private void MyFolderCreate(string myfolder)
{
    string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // User Documents 폴더
    string MyPath = UserPath + "\\" + myfolder;
    if (!Directory.Exists(MyPath))
    {
        System.IO.Directory.CreateDirectory(MyPath);
    }
}


아래는 폴더 경로 정보와 폴더 생성를 분리하여 처리한 코드이다.

public static void MyFolderCreate(string myfolder)
{
    string MyPath = MyFolder(myfolder);
    if (!Directory.Exists(MyPath))
    {
        Directory.CreateDirectory(MyPath);
    }
}

public static string MyFolder(string myfolder)
{
    string UserPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // User Documents 폴더
    return UserPath + "\\" + myfolder;
}


=== 폴더 삭제 코드 ===


public static void MyFolderDelete(string path)
{
    DeleteDirectory(path, false);
}

public static void DeleteDirectory(string path, bool recursive)
{
    if (recursive)
    {
        var subfolders = Directory.GetDirectories(path);
        foreach (var subfolder in subfolders)
        {
            DeleteDirectory(subfolder, recursive);
        }
    }

    // Get all files of the folder
    var files = Directory.GetFiles(path);
    foreach (var file in files)
    {
        var attribute = File.GetAttributes(file);
        if ((attribute & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
        {
            File.SetAttributes(file, attribute ^ FileAttributes.ReadOnly);
        }
        File.Delete(file);
    }
    Directory.Delete(path);
}


폴더 삭제코드 출처 : http://caioproiete.net/en/csharp-delete-folder-including-its-sub-folders-and-files-even-if-marked-as-read-only/


'C# > 문법 및 기능' 카테고리의 다른 글

C# NameValueCollection  (0) 2016.03.20
C# Dictionary 와 comboBox 연결  (0) 2016.02.08
C# 시간 메소드  (0) 2016.01.15
C# 파일 입출력 개념 정리  (0) 2016.01.05
C# int.TryParse  (0) 2015.12.25
블로그 이미지

Link2Me

,