programing

디렉토리에 폴더가 있는지 확인하고 C#을 사용하여 폴더를 만듭니다.

lastcode 2023. 5. 17. 23:14
반응형

디렉토리에 폴더가 있는지 확인하고 C#을 사용하여 폴더를 만듭니다.

디렉토리인지 확인하려면 어떻게 해야 합니까?C:/이름이 지정된 폴더 포함MP_Upload폴더가 없으면 자동으로 폴더를 생성하시겠습니까?

Visual Studio 2005 C#을 사용하고 있습니다.

이는 다음과 같은 도움이 됩니다.

using System.IO;
...

string path = @"C:\MP_Upload";
if(!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}
using System.IO;
...

Directory.CreateDirectory(@"C:\MP_Upload");

디렉터리.CreateDirectory는 사용자가 원하는 작업을 수행합니다.디렉토리가 아직 존재하지 않는 경우 디렉토리를 작성합니다.먼저 명시적인 확인을 할 필요가 없습니다.

이미 존재하거나 경로의 일부가 올바르지 않은 경우를 제외하고 경로에 지정된 모든 디렉토리가 만들어집니다.경로 매개 변수는 파일 경로가 아닌 디렉터리 경로를 지정합니다.디렉터리가 이미 있는 경우 이 메서드는 아무 작업도 수행하지 않습니다.

필요한 경우 경로를 따라 모든 디렉토리가 생성됩니다.CreateDirectory(@"C:\a\b\c\d")해도 충분합니다.C:\a아직 존재하지 않습니다.)


디렉터리 선택에 대한 주의 사항을 추가하겠습니다. 시스템 파티션 루트 바로 아래에 폴더 만들기C:\눈살을 찌푸립니다.사용자가 폴더를 선택하거나 폴더를 만드는 것을 고려합니다.%APPDATA%또는%LOCALAPPDATA%대신 환경을 사용합니다.이에 대한 폴더 경로 가져오기).환경의 MSDN 페이지입니다.특수 폴더 열거에는 특수 운영 체제 폴더와 해당 용도의 목록이 포함됩니다.

if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
     System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}

이것은 효과가 있을 것입니다.

if(!Directory.Exists(@"C:\MP_Upload")) {
    Directory.CreateDirectory(@"C:\MP_Upload");
}
using System;
using System.IO;
using System.Windows.Forms;

namespace DirCombination 
{
    public partial class DirCombination : Form
    {
        private const string _Path = @"D:/folder1/foler2/folfer3/folder4/file.txt";
        private string _finalPath = null;
        private string _error = null;

        public DirCombination()
        {
            InitializeComponent();

            if (!FSParse(_Path))
                Console.WriteLine(_error);
            else
                Console.WriteLine(_finalPath);
        }

        private bool FSParse(string path)
        {
            try
            {
                string[] Splited = path.Replace(@"//", @"/").Replace(@"\\", @"/").Replace(@"\", "/").Split(':');
                string NewPath = Splited[0] + ":";
                if (Directory.Exists(NewPath))
                {                    
                    string[] Paths = Splited[1].Substring(1).Split('/');

                    for (int i = 0; i < Paths.Length - 1; i++)
                    {
                        NewPath += "/";
                        if (!string.IsNullOrEmpty(Paths[i]))
                        {
                            NewPath += Paths[i];
                            if (!Directory.Exists(NewPath))
                                Directory.CreateDirectory(NewPath);
                        }
                    }

                    if (!string.IsNullOrEmpty(Paths[Paths.Length - 1]))
                    {
                        NewPath += "/" + Paths[Paths.Length - 1];
                        if (!File.Exists(NewPath))
                            File.Create(NewPath);
                    }
                    _finalPath = NewPath;
                    return true;
                }
                else
                {
                    _error = "Drive is not exists!";
                    return false;
                }
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return false;
            }
        }
    }
}
    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

언급URL : https://stackoverflow.com/questions/9092160/check-if-a-folder-exist-in-a-directory-and-create-them-using-c-sharp

반응형