다음을 통해 공유


방법: 파일 또는 폴더 만들기(C# 프로그래밍 가이드)

이 예제에서는 컴퓨터에 폴더와 하위 폴더를 만든 다음 하위 폴더에 새 파일을 만들고 해당 파일에 몇 가지 데이터를 씁니다.

예제

public class CreateFileOrFolder
{
    static void Main()
    {
        // Specify a "currently active folder"
        string activeDir = @"c:\testdir2";

        //Create a new subfolder under the current active folder
        string newPath = System.IO.Path.Combine(activeDir, "mySubDir");

        // Create the subfolder
        System.IO.Directory.CreateDirectory(newPath);

        // Create a new file name. This example generates
        // a random string.
        string newFileName = System.IO.Path.GetRandomFileName();

        // Combine the new file name with the path
        newPath = System.IO.Path.Combine(newPath, newFileName);

        // Create the file and write to it.
        // DANGER: System.IO.File.Create will overwrite the file
        // if it already exists. This can occur even with
        // random file names.
        if (!System.IO.File.Exists(newPath))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(newPath))
            {
                for (byte i = 0; i < 100; i++)
                {
                    fs.WriteByte(i);
                }
            }
        }

        // Read data back from the file to prove
        // that the previous code worked.
        try
        {
            byte[] readBuffer = System.IO.File.ReadAllBytes(newPath);
            foreach (byte b in readBuffer)
            {
                Console.WriteLine(b);
            }
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}

폴더가 이미 있을 경우 CreateDirectory는 아무 작업도 수행하지 않으며 예외가 throw되지 않습니다. 하지만 File.Create는 모든 기존 파일을 덮어씁니다. 기존 파일을 덮어쓰지 않으려면 OpenWrite 메서드를 사용하고 파일을 덮어쓰지 않고 추가하는 FileMode.OpenOrCreate 옵션을 지정할 수 있습니다.

다음 조건에서 예외가 발생합니다.

  • 폴더 이름의 형식이 잘못된 경우. 예를 들어, 파일 이름에 잘못된 문자가 포함되어 있거나 파일 이름이 공백인 경우(ArgumentException 클래스) Path 클래스를 사용하여 유효한 경로 이름을 만듭니다.

  • 만들 폴더의 부모 폴더가 읽기 전용인 경우(IOException 클래스)

  • 폴더 이름이 null인 경우(ArgumentNullException 클래스)

  • 폴더 이름이 너무 긴 경우(PathTooLongException 클래스)

  • 폴더 이름이 콜론 ":"인 경우(PathTooLongException 클래스)

보안

부분 신뢰 상황에서는 SecurityException 클래스의 인스턴스가 throw될 수 있습니다.

사용자에게 폴더를 만들 권한이 없는 경우에는 예제에서 UnauthorizedAccessException 클래스의 인스턴스가 throw됩니다.

참고 항목

참조

System.IO

개념

C# 프로그래밍 가이드

기타 리소스

파일 시스템 및 레지스트리(C# 프로그래밍 가이드)