반응형

▶ 상황 1 (권한관리 없음, 권한관리가 있는 버전을 아래쪽에 있습니다.)

C# 으로 폴더 유무를 확인하고 없을 경우 폴더를 생성해야 합니다.

(폴더를 생성할 수 있는 적절한 권한이 있어야 생성됩니다.)


Root 폴더는 시스템에서 정해진 곳을 기준으로 생성하며, 하위 풀도만 사용자에게 입력받아 생성합니다.

아래의 경우 txtRoot 는 시스템에 정의된 Root 폴더 경로가 저장되어 있으며 txtFolderName 은 사용자에게 입력받는 경로입니다.


사용자에게 입력받은 경로에 대하여 공백 등 예외처리는 진행하지 않았습니다.


▶ 소스

     

      try

{

    string sFulllPath = Path.Combine(txtRoot.Text, txtFolderName.Text);


    DirectoryInfo dir = new DirectoryInfo(sFullPath);  

                                                                                                                            

    if (dir.Exists == false) 

    {

        dir.Create(); 

    }

}

catch(Exception ex)

{

}



▶ 추가설명

두개의 폴더를 합치기 위해서 "+" 를 사용하지 않고 Path.Combine 을 사용하여 "//" 폴더 구분자를 신경쓰지 않고 합칠 수 있습니다.

유효하지 않은 구분 기호 문자로 끝나거나 공백이 포함될 경우 알아서 처리를 해줘서 일부러 예외처리를 하지 않아도 됩니다.

네임스페이스는 System.IO 며 문자 배열도 받아 여러 문자를 합칠 수 있습니다.




▶ 상황 2 (권한관리 있음)

폴더를 만들고 특정 권한을 부여하고 싶다면 아래 코드를 추가하여 권한을 추가해야 합니다.


▶ 소스

 

protected void btnCreate_Click(object sender, EventArgs e)

{

    try

    {

        string fullPath = Path.Combine(txtRoot.Text, txtFolder.Text);

        DirectoryInfo dir = new DirectoryInfo(fullPath);


        if (dir.Exists == false)

        {

            DirectorySecurity dirSecu = SetDirectorySecurity(dir);

            dir.Create(dirSecu); //만들어진 권한 룰을 기반으로 폴더를 생성한다.

        }

        else

        {

            DirectorySecurity dirSecu = SetDirectorySecurity(dir);

            dir.SetAccessControl(dirSecu);

        }

    }

    catch (Exception ex)

    {

        txtResult.Text = ex.Message;

    }

}



protected DirectorySecurity SetDirectorySecurity(DirectoryInfo dir)

{

    DirectorySecurity securityRules = null;

    try {

        securityRules = dir.Parent.GetAccessControl(); //상위 폴더의 권한을 가져와 권한 룰을 생성한다.


        securityRules.AddAccessRule(new FileSystemAccessRule(@"[계정]", 

            FileSystemRights.ReadAndExecute,

            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,

            PropagationFlags.None, AccessControlType.Allow));  //읽기 및 복사 권한을 갖는 권한을 추가한다.


        securityRules.AddAccessRule(new FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, 

            FileSystemRights.FullControl,

            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,

            PropagationFlags.None, AccessControlType.Allow));  //현재 계정을 Full 권한을 갖는 권한을 추가한다.

    }

    catch(Exception ex)

    {

        throw ex;

    }

    return securityRules;

}






반응형

+ Recent posts