달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2016. 8. 25. 15:39

파일 시스템 및 레지스트리 프로그래밍/C#2016. 8. 25. 15:39

https://msdn.microsoft.com/ko-kr/library/2kzb96fk.aspx


방법: 디렉터리 트리 반복


1. "디렉터리 트리 반복"이란 깊이에 관계없이 지정된 루트 폴더 아래에 있는 각 중첩 하위 디렉터리에서 각 파일에 액세스한다는 의미입니다.

2. 이때 각 파일을 반드시 열어야 하는 것은 아닙니다.

3. 파일이나 하위 디렉터리의 이름만 string으로 검색하거나 System.IO.FileInfo 또는 System.IO.DirectoryInfo 개체의 형태로 추가 정보를 검색할 수 있습니다.


참고

Windows에서 "디렉터리"와 "폴더"라는 용어는 같은 의미로 사용됩니다. 대부분의 설명서와 사용자 인터페이스 텍스트에서는 "폴더"라는 용어가 사용되지만 .NET Framework 클래스 라이브러리에서는 "디렉터리"라는 용어가 사용됩니다.


4. 지정된 루트 아래에 있는 모든 디렉터리에 대한 액세스 권한이 있는 경우가 가장 간단하며, 이 경우에는 System.IO.SearchOption.AllDirectories 플래그를 사용할 수 있습니다.

5. 이 플래그는 지정된 패턴과 일치하는 모든 중첩 하위 디렉터리를 반환합니다.

6. 다음 예제에서는 이 플래그를 사용하는 방법을 보여 줍니다.


root.GetDirectories("*.*", System.IO.SearchOption.AllDirectories);


7. 이 방식의 단점은 지정된 루트 아래에 있는 하위 디렉터리 중 하나가 DirectoryNotFoundException 또는 UnauthorizedAccessException을 발생시키면 전체 메서드가 실패하고 디렉터리가 반환되지 않는다는 것입니다.

8. 이것은 GetFiles 메서드를 사용할 경우에도 마찬가지입니다.

9. 특정 하위 폴더에서 이러한 예외를 처리해야 한다면 다음 예제에서 볼 수 있는 것처럼 디렉터리 트리를 수동으로 탐색해야 합니다.

10. 디렉터리 트리를 수동으로 탐색할 때 하위 디렉터리를 먼저(전위 탐색) 처리하거나 파일을 먼저(후위 탐색) 처리할 수 있습니다.

11. 전위 탐색을 수행할 경우 폴더 자체에 들어 있는 파일을 반복하기 전에 먼저 현재 폴더 아래에 있는 전체 트리를 탐색합니다.

12. 이 문서의 뒷부분에 있는 예제에서는 후위 탐색을 수행하지만 전위 탐색을 수행하도록 수정하는 것은 간단합니다.

13. 다른 옵션은 재귀를 사용할지 스택 기반 탐색을 사용할지 결정하는 것입니다.

14. 이 문서의 뒷부분에 있는 예제에서는 두 방식을 모두 보여 줍니다.

15. 파일과 폴더에 대한 다양한 작업을 수행해야 한다면 단일 대리자를 통해 호출할 수 있는 별도의 함수로 작업을 리팩터링하여 이 예제를 모듈화할 수 있습니다.


참고

1. NTFS 파일 시스템은 연결 지점, 기호화된 링크 및 하드 링크의 형태로 재분석 지점을 포함할 수 있습니다.

2. GetFiles 및 GetDirectories 등의 .NET Framework 메서드는 재분석 지점 아래에 있는 하위 디렉터리를 반환하지 않습니다.

3. 이 동작은 두 재분석 지점이 상호 참조하는 경우 무한 루프에 빠지지 않도록 보호합니다.

4. 일반적으로 재분석 지점으로 작업할 때에는 실수로 파일을 수정하거나 삭제하지 않도록 특히 주의해야 합니다.

5. 재분석 지점에 대한 정밀한 제어가 필요한 경우에는 적절한 Win32 파일 시스템 메서드를 직접 호출하는 플랫폼 호출이나 네이티브 코드를 사용하십시오.


예제

1. 다음 예제에서는 재귀를 사용하여 디렉터리 트리를 탐색하는 방법을 보여 줍니다.

2. 재귀는 적절한 방식이기는 하지만 디렉터리 트리의 규모가 크고 복잡하게 중첩되어 있는 경우 스택 오버플로 예외를 발생시킬 위험이 있습니다.

3. 처리되는 특정한 예외와 각 파일이나 폴더에 수행되는 특정 작업은 예제로만 제공됩니다.

4. 따라서 해당 요구 사항에 맞게 이 코드를 수정해야 합니다. 자세한 내용은 코드의 주석을 참조하십시오.


public class RecursiveFileSearch
{
    static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();

    static void Main()
    {
        // Start with drives if you have to search the entire computer.
        string[] drives = System.Environment.GetLogicalDrives();

        foreach (string dr in drives)
        {
            System.IO.DriveInfo di = new System.IO.DriveInfo(dr);

            // Here we skip the drive if it is not ready to be read. This
            // is not necessarily the appropriate action in all scenarios.
            if (!di.IsReady)
            {
                Console.WriteLine("The drive {0} could not be read", di.Name);
                continue;
            }
            System.IO.DirectoryInfo rootDir = di.RootDirectory;
            WalkDirectoryTree(rootDir);
        }

        // Write out all the files that could not be processed.
        Console.WriteLine("Files with restricted access:");
        foreach (string s in log)
        {
            Console.WriteLine(s);
        }
        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key");
        Console.ReadKey();
    }

    static void WalkDirectoryTree(System.IO.DirectoryInfo root)
    {
        System.IO.FileInfo[] files = null;
        System.IO.DirectoryInfo[] subDirs = null;

        // First, process all the files directly under this folder
        try
        {
            files = root.GetFiles("*.*");
        }
        // This is thrown if even one of the files requires permissions greater
        // than the application provides.
        catch (UnauthorizedAccessException e)
        {
            // This code just writes out the message and continues to recurse.
            // You may decide to do something different here. For example, you
            // can try to elevate your privileges and access the file again.
            log.Add(e.Message);
        }

        catch (System.IO.DirectoryNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }

        if (files != null)
        {
            foreach (System.IO.FileInfo fi in files)
            {
                // In this example, we only access the existing FileInfo object. If we
                // want to open, delete or modify the file, then
                // a try-catch block is required here to handle the case
                // where the file has been deleted since the call to TraverseTree().
                Console.WriteLine(fi.FullName);
            }

            // Now find all the subdirectories under this directory.
            subDirs = root.GetDirectories();

            foreach (System.IO.DirectoryInfo dirInfo in subDirs)
            {
                // Resursive call for each subdirectory.
                WalkDirectoryTree(dirInfo);
            }
        }            
    }
}


예제

1. 다음 예제에서는 재귀를 사용하지 않고 디렉터리 트리에서 파일 및 폴더를 반복하는 방법을 보여 줍니다.

2. 이 방법에서는 LIFO(후입선출) 스택인 제네릭 Stack<T> 컬렉션 형식을 사용합니다.

3. 처리되는 특정한 예외와 각 파일이나 폴더에 수행되는 특정 작업은 예제로만 제공됩니다.

4. 따라서 해당 요구 사항에 맞게 이 코드를 수정해야 합니다.

5. 자세한 내용은 코드의 주석을 참조하십시오.


public class StackBasedIteration
{
    static void Main(string[] args)
    {
        // Specify the starting folder on the command line, or in 
        // Visual Studio in the Project > Properties > Debug pane.
        TraverseTree(args[0]);

        Console.WriteLine("Press any key");
        Console.ReadKey();
    }

    public static void TraverseTree(string root)
    {
        // Data structure to hold names of subfolders to be
        // examined for files.
        Stack<string> dirs = new Stack<string>(20);

        if (!System.IO.Directory.Exists(root))
        {
            throw new ArgumentException();
        }
        dirs.Push(root);

        while (dirs.Count > 0)
        {
            string currentDir = dirs.Pop();
            string[] subDirs;
            try
            {
                subDirs = System.IO.Directory.GetDirectories(currentDir);
            }
            // An UnauthorizedAccessException exception will be thrown if we do not have
            // discovery permission on a folder or file. It may or may not be acceptable 
            // to ignore the exception and continue enumerating the remaining files and 
            // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
            // will be raised. This will happen if currentDir has been deleted by
            // another application or thread after our call to Directory.Exists. The 
            // choice of which exceptions to catch depends entirely on the specific task 
            // you are intending to perform and also on how much you know with certainty 
            // about the systems on which this code will run.
            catch (UnauthorizedAccessException e)
            {                    
                Console.WriteLine(e.Message);
                continue;
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }

            string[] files = null;
            try
            {
                files = System.IO.Directory.GetFiles(currentDir);
            }

            catch (UnauthorizedAccessException e)
            {

                Console.WriteLine(e.Message);
                continue;
            }

            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }
            // Perform the required action on each file here.
            // Modify this block to perform your required task.
            foreach (string file in files)
            {
                try
                {
                    // Perform whatever action is required in your scenario.
                    System.IO.FileInfo fi = new System.IO.FileInfo(file);
                    Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                }
                catch (System.IO.FileNotFoundException e)
                {
                    // If file was deleted by a separate application
                    //  or thread since the call to TraverseTree()
                    // then just continue.
                    Console.WriteLine(e.Message);
                    continue;
                }
            }

            // Push the subdirectories onto the stack for traversal.
            // This could also be done before handing the files.
            foreach (string str in subDirs)
                dirs.Push(str);
        }
    }
}


6. 응용 프로그램에 폴더를 열 수 있는 권한이 있는지 확인하기 위해 모든 폴더를 테스트하는 작업은 시간이 너무 많이 걸립니다.

7. 따라서 이 코드 예제에서는 작업의 해당 부분을 try/catch 블록으로 묶기만 했습니다.

8. 폴더에 대한 액세스가 거부된 경우 권한을 상승시키고 다시 액세스할 수 있도록 catch 블록을 수정할 수 있습니다.

9. 일반적으로 응용 프로그램을 알 수 없는 상태로 두지 않고 처리할 수 있는 예외만 catch합니다.

10. 디렉터리 트리의 내용을 메모리나 디스크에 저장해야 하는 경우 각 파일의 FullName 속성(string 형식)만 저장하는 것이 좋습니다.

11. 그런 다음 필요에 따라 이 문자열을 사용하여 새 FileInfo 또는 DirectoryInfo 개체를 만들거나 추가적인 처리가 필요한 파일을 열 수 있습니다.


강력한 프로그래밍

1. 강력한 파일 반복 코드에서는 파일 시스템의 여러 가지 복잡한 특성을 고려해야 합니다.

2. 자세한 내용은 NTFS Technical Reference를 참조하십시오.




방법: 파일, 폴더 및 드라이브에 대한 정보 가져오기


1. .NET Framework에서 다음과 같은 클래스를 사용하여 파일 시스템 정보에 액세스할 수 있습니다.

1) System.IO.FileInfo

2) System.IO.DirectoryInfo

3) System.IO.DriveInfo

4) System.IO.Directory

5) System.IO.File

2. FileInfo 및 DirectoryInfo 클래스는 파일 또는 디렉터리를 나타내며 NTFS 파일 시스템이 지원하는 많은 파일 특성을 노출하는 속성을 포함합니다.

3. 또한 파일 및 폴더 열기, 닫기, 이동, 삭제를 위한 메서드도 포함합니다.

4. 다음과 같이 생성자에 파일, 폴더 또는 드라이브 이름을 나타내는 문자열을 전달하여 이러한 클래스의 인스턴스를 만들 수 있습니다.


System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");


5. DirectoryInfo.GetDirectories, DirectoryInfo.GetFiles 및 DriveInfo.RootDirectory를 호출하여 파일, 폴더 또는 드라이브 이름을 얻을 수도 있습니다.

6. System.IO.Directory 및 System.IO.File 클래스는 디렉터리 및 파일에 대한 정보를 검색하는 static 메서드를 제공합니다.


예제

1. 다음 예제에서는 파일 및 폴더 정보에 액세스하는 여러 가지 방법을 보여 줍니다.


class FileSysInfo
{
    static void Main()
    {
        // You can also use System.Environment.GetLogicalDrives to
        // obtain names of all logical drives on the computer.
        System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");
        Console.WriteLine(di.TotalFreeSpace);
        Console.WriteLine(di.VolumeLabel);

        // Get the root directory and print out some information about it.
        System.IO.DirectoryInfo dirInfo = di.RootDirectory;
        Console.WriteLine(dirInfo.Attributes.ToString());

        // Get the files in the directory and print out some information about them.
        System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");


        foreach (System.IO.FileInfo fi in fileNames)
        {
            Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
        }

        // Get the subdirectories directly that is under the root.
        // See "How to: Iterate Through a Directory Tree" for an example of how to
        // iterate through an entire tree.
        System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");

        foreach (System.IO.DirectoryInfo d in dirInfos)
        {
            Console.WriteLine(d.Name);
        }

        // The Directory and File classes provide several static methods
        // for accessing files and directories.

        // Get the current application directory.
        string currentDirName = System.IO.Directory.GetCurrentDirectory();
        Console.WriteLine(currentDirName);           

        // Get an array of file names as strings rather than FileInfo objects.
        // Use this method when storage space is an issue, and when you might
        // hold on to the file name reference for a while before you try to access
        // the file.
        string[] files = System.IO.Directory.GetFiles(currentDirName, "*.txt");

        foreach (string s in files)
        {
            // Create the FileInfo object only when needed to ensure
            // the information is as current as possible.
            System.IO.FileInfo fi = null;
            try
            {
                 fi = new System.IO.FileInfo(s);
            }
            catch (System.IO.FileNotFoundException e)
            {
                // To inform the user and continue is
                // sufficient for this demonstration.
                // Your application may require different behavior.
                Console.WriteLine(e.Message);
                continue;
            }
            Console.WriteLine("{0} : {1}",fi.Name, fi.Directory);
        }

        // Change the directory. In this case, first check to see
        // whether it already exists, and create it if it does not.
        // If this is not appropriate for your application, you can
        // handle the System.IO.IOException that will be raised if the
        // directory cannot be found.
        if (!System.IO.Directory.Exists(@"C:\Users\Public\TestFolder\"))
        {
            System.IO.Directory.CreateDirectory(@"C:\Users\Public\TestFolder\");
        }

        System.IO.Directory.SetCurrentDirectory(@"C:\Users\Public\TestFolder\");

        currentDirName = System.IO.Directory.GetCurrentDirectory();
        Console.WriteLine(currentDirName);

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


강력한 프로그래밍

1. 사용자가 지정한 경로 문자열을 처리할 때 다음과 같은 예외 상황을 처리해야 합니다.

1) 파일 이름의 형식이 잘못된 경우. 예를 들어 파일 이름에 잘못된 문자가 들어 있거나 공백이 있을 수 있습니다.

2) 경로 이름이 null인 경우

3) 파일 이름이 시스템에 정의된 최대 길이보다 긴 경우

4) 파일 이름에 콜론(:)이 있는 경우

2. 지정된 파일을 읽을 수 있는 충분한 권한이 응용 프로그램에 없으면 경로의 존재 여부와 상관없이 Exists 메서드에서 false를 반환합니다.

3. 이때 메서드는 예외를 throw하지 않습니다.



방법: 파일 또는 폴더 만들기


1. 프로그램으로 컴퓨터에 폴더를 만들고, 하위 폴더를 만들고, 하위 폴더에 특정 파일을 만든 다음, 해당 파일에 데이터를 쓸 수 있습니다.


public class CreateFileOrFolder
{
    static void Main()
    {
        // Specify a name for your top-level folder.
        string folderName = @"c:\Top-Level Folder";

        // To create a string that specifies the path to a subfolder under your 
        // top-level folder, add a name for the subfolder to folderName.
        string pathString = System.IO.Path.Combine(folderName, "SubFolder");

        // You can write out the path name directly instead of using the Combine
        // method. Combine just makes the process easier.
        string pathString2 = @"c:\Top-Level Folder\SubFolder2";

        // You can extend the depth of your path if you want to.
        //pathString = System.IO.Path.Combine(pathString, "SubSubFolder");

        // Create the subfolder. You can verify in File Explorer that you have this
        // structure in the C: drive.
        //    Local Disk (C:)
        //        Top-Level Folder
        //            SubFolder
        System.IO.Directory.CreateDirectory(pathString);

        // Create a file name for the file you want to create. 
        string fileName = System.IO.Path.GetRandomFileName();

        // This example uses a random string for the name, but you also can specify
        // a particular name.
        //string fileName = "MyNewFile.txt";

        // Use Combine again to add the file name to the path.
        pathString = System.IO.Path.Combine(pathString, fileName);

        // Verify the path that you have constructed.
        Console.WriteLine("Path to my file: {0}\n", pathString);

        // Check that the file doesn't already exist. If it doesn't exist, create
        // the file and write integers 0 - 99 to it.
        // DANGER: System.IO.File.Create will overwrite the file if it already exists.
        // This could happen even with random file names, although it is unlikely.
        if (!System.IO.File.Exists(pathString))
        {
            using (System.IO.FileStream fs = System.IO.File.Create(pathString))
            {
                for (byte i = 0; i < 100; i++)
                {
                    fs.WriteByte(i);
                }
            }
        }
        else
        {
            Console.WriteLine("File \"{0}\" already exists.", fileName);
            return;
        }

        // Read and display the data from your file.
        try
        {
            byte[] readBuffer = System.IO.File.ReadAllBytes(pathString);
            foreach (byte b in readBuffer)
            {
                Console.Write(b + " ");
            }
            Console.WriteLine();
        }
        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();
    }
    // Sample output:

    // Path to my file: c:\Top-Level Folder\SubFolder\ttxvauxe.vv0

    //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
    //30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    // 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 8
    //3 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
}


2. 폴더가 이미 있을 경우 CreateDirectory는 아무 작업도 수행하지 않으며 예외가 throw되지 않습니다.

3. 그러나 File.Create이 기존 파일을 새 파일로 바꿉니다.

4. 예제는 기존 파일이 대체되지 않도록 if-else 문을 사용합니다.

5. 예제를 다음과 같이 변경하여 특정 이름을 가진 파일이 이미 있는지 여부를 기준으로 다른 결과를 지정할 수 있습니다.

6. 이러한 파일이 없으면 코드가 파일을 하나 만듭니다.

7. 이러한 파일이 있으면 코드가 파일에 데이터를 추가합니다.

1) non-random 파일 이름을 지정합니다.


// Comment out the following line.
//string fileName = System.IO.Path.GetRandomFileName();

// Replace that line with the following assignment.
string fileName = "MyNewFile.txt";


2) if-else 문을 다음 코드의 using 문으로 바꿉니다.


using (System.IO.FileStream fs = new System.IO.FileStream(pathString, FileMode.Append)) 
{
    for (byte i = 0; i < 100; i++)
    {
        fs.WriteByte(i);
    }
}


8. 데이터가 파일에 추가될 때마다 확인하려면 예제를 여러 번 실행합니다.

9. 사용자가 시도할 수 있는 더 많은 FileMode 값은 FileMode을 참조하십시오.

10. 다음 조건에서 예외가 발생할 수 있습니다.

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

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

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

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

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


.NET Framework 보안

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

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




파일 및 폴더 복사, 삭제 및 이동


1. 다음 예제에서는 System.IO 네임스페이스의 System.IO.File, System.IO.Directory, System.IO.FileInfo 및 System.IO.DirectoryInfo 클래스를 사용하여 파일 및 폴더를 동기화된 방식으로 복사, 이동 및 삭제하는 방법을 보여 줍니다.

2. 이러한 예제에서는 진행률 표시줄이나 다른 사용자 인터페이스는 제공하지 않습니다.

3. 표준 진행률 대화 상자를 제공하려면 방법: 파일 작업에 대한 진행률 대화 상자 제공(C# 프로그래밍 가이드)을 참조하십시오.

4. System.IO.FileSystemWatcher를 사용하면 여러 파일을 처리할 때 진행률을 계산할 수 있는 이벤트를 제공할 수 있습니다.

5. 또 다른 방법은 Windows 셸에서 파일 관련 메서드를 호출하는 플랫폼 호출을 사용하는 것입니다.

6. 이러한 파일 작업을 비동기적으로 수행하는 방법에 대한 자세한 내용은 비동기 파일 I/O를 참조하십시오.


예제

1. 다음 예제에서는 파일 및 디렉터리를 복사하는 방법을 보여 줍니다.


// Simple synchronous file copy operations with no user interface.
// To run this sample, first create the following directories and files:
// C:\Users\Public\TestFolder
// C:\Users\Public\TestFolder\test.txt
// C:\Users\Public\TestFolder\SubDir\test.txt
public class SimpleFileCopy
{
    static void Main()
    {
        string fileName = "test.txt";
        string sourcePath = @"C:\Users\Public\TestFolder";
        string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

        // Use Path class to manipulate file and directory paths.
        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);

        // To copy a folder's contents to a new location:
        // Create a new target folder, if necessary.
        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
        }

        // To copy a file to another location and 
        // overwrite the destination file if it already exists.
        System.IO.File.Copy(sourceFile, destFile, true);

        // To copy all the files in one directory to another directory.
        // Get the files in the source folder. (To recursively iterate through
        // all subfolders under the current directory, see
        // "How to: Iterate Through a Directory Tree.")
        // Note: Check for target path was performed previously
        //       in this code example.
        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);

            // Copy the files and overwrite destination files if they already exist.
            foreach (string s in files)
            {
                // Use static Path methods to extract only the file name from the path.
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);
            }
        }
        else
        {
            Console.WriteLine("Source path does not exist!");
        }

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


예제

1. 다음 예제에서는 파일 및 디렉터리를 이동하는 방법을 보여 줍니다.


// Simple synchronous file move operations with no user interface.
public class SimpleFileMove
{
    static void Main()
    {
        string sourceFile = @"C:\Users\Public\public\test.txt";
        string destinationFile = @"C:\Users\Public\private\test.txt";

        // To move a file or folder to a new location:
        System.IO.File.Move(sourceFile, destinationFile);

        // To move an entire directory. To programmatically modify or combine
        // path strings, use the System.IO.Path class.
        System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
    }
}


예제

1. 다음 예제에서는 파일 및 디렉터리를 삭제하는 방법을 보여 줍니다.


// Simple synchronous file deletion operations with no user interface.
// To run this sample, create the following files on your drive:
// C:\Users\Public\DeleteTest\test1.txt
// C:\Users\Public\DeleteTest\test2.txt
// C:\Users\Public\DeleteTest\SubDir\test2.txt

public class SimpleFileDelete
{
    static void Main()
    {
        // Delete a file by using File class static method...
        if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
        {
            // Use a try block to catch IOExceptions, to
            // handle the case of the file already being
            // opened by another process.
            try
            {
                System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
        }

        // ...or by using FileInfo instance method.
        System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt");
        try
        {
            fi.Delete();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // Delete a directory. Must be writable or empty.
        try
        {
            System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest");
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
        // Delete a directory and all subdirectories with Directory static method...
        if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest"))
        {
            try
            {
                System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true);
            }

            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        // ...or with DirectoryInfo instance method.
        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public");
        // Delete this dir and all subdirs.
        try
        {
            di.Delete(true);
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

    }
}




방법: 파일 작업에 대한 진행률 대화 상자 제공


1. Microsoft.VisualBasic 네임스페이스에서 CopyFile(String, String, UIOption) 메서드를 사용하면 Windows에서 파일 작업에 대한 진행률을 표시하는 표준 대화 상자를 제공할 수 있습니다.


참고

1. 일부 Visual Studio 사용자 인터페이스 요소의 경우 다음 지침에 설명된 것과 다른 이름 또는 위치가 시스템에 표시될 수 있습니다.

2. 이러한 요소는 사용하는 Visual Studio 버전 및 설정에 따라 결정됩니다.

3. 자세한 내용은 Visual Studio IDE 개인 설정을 참조하십시오.


Visual Studio에서 참조를 추가하려면

1. 메뉴 모음에서 프로젝트, 참조 추가를 선택합니다.

2. 참조 관리자 대화 상자가 나타납니다.

3. 어셈블리 영역에서 프레임워크가 아직 선택되어 있지 않으면 프레임워크를 선택합니다.

4. 이름 목록에서, Microsoft.VisualBasic 확인란을 선택하고 나서, 확인 단추를 선택하면 대화 상자가 닫힙니다.


예제

1. 다음 코드에서는 sourcePath에서 지정하는 디렉터리를 destinationPath에서 지정하는 디렉터리로 복사합니다.

2. 이 코드에서는 또한 작업이 끝날 때까지 남은 추정 시간을 보여 주는 표준 대화 상자도 제공합니다.


// The following using directive requires a project reference to Microsoft.VisualBasic.
using Microsoft.VisualBasic.FileIO;

class FileProgress
{
    static void Main()
    {
        // Specify the path to a folder that you want to copy. If the folder is small, 
        // you won't have time to see the progress dialog box.
        string sourcePath = @"C:\Windows\symbols\";
        // Choose a destination for the copied files.
        string destinationPath = @"C:\TestFolder";

        FileSystem.CopyDirectory(sourcePath, destinationPath,
            UIOption.AllDialogs);
    }
}




방법: 텍스트 파일에 쓰기


1. 다음 코드 예제에서는 파일에 텍스트를 쓰는 여러 가지 방법을 보여 줍니다.

2. 처음 두 예제에서는 System.IO.File 클래스에서 정적 편의 메서드를 사용하여 IEnumerable<string>의 각 요소와 문자열을 텍스트 파일에 씁니다.

3. 예제 3에서는 파일에 쓸 때 각 줄을 개별적으로 처리해야 하는 경우 파일에 텍스트를 추가하는 방법을 보여 줍니다.

4. 예제 1-3에서는 파일의 기존 내용을 모두 덮어쓰지만 예제 4에서는 기존 파일에 텍스트를 추가하는 방법을 보여 줍니다.

5. 이 네 예제에서는 모두 파일에 문자열 리터럴을 쓰지만 대개는 Format 메서드를 사용합니다.

6. 이 메서드는 필드에서 값을 오른쪽 또는 왼쪽 맞춤으로 정렬하고 안쪽 여백을 포함하거나 포함하지 않는 등 다양한 형식의 값을 쓰기 위한 많은 컨트롤을 포함합니다.

7. C# 문자열 보간 기능을 사용할 수도 있습니다.


class WriteTextFile
{
    static void Main()
    {

        // These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
        // You can modify the path if necessary.


        // Example #1: Write an array of strings to a file.
        // Create a string array that consists of three lines.
        string[] lines = { "First line", "Second line", "Third line" };
        // WriteAllLines creates a file, writes a collection of strings to the file,
        // and then closes the file.  You do NOT need to call Flush() or Close().
        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);


        // Example #2: Write one string to a text file.
        string text = "A class is the most powerful data type in C#. Like a structure, " +
                       "a class defines the data and behavior of the data type. ";
        // WriteAllText creates a file, writes the specified string to the file,
        // and then closes the file.    You do NOT need to call Flush() or Close().
        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

        // Example #3: Write only some strings in an array to a file.
        // The using statement automatically flushes AND CLOSES the stream and calls 
        // IDisposable.Dispose on the stream object.
        // NOTE: do not use FileStream for text files because it writes bytes, but StreamWriter
        // encodes the output as text.
        using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }

        // Example #4: Append new text to an existing file.
        // The using statement automatically flushes AND CLOSES the stream and calls 
        // IDisposable.Dispose on the stream object.
        using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
        {
            file.WriteLine("Fourth line");
        }
    }
}
 //Output (to WriteLines.txt):
 //   First line
 //   Second line
 //   Third line

 //Output (to WriteText.txt):
 //   A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.

 //Output to WriteLines2.txt after Example #3:
 //   First line
 //   Third line

 //Output to WriteLines2.txt after Example #4:
 //   First line
 //   Third line
 //   Fourth line


강력한 프로그래밍

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

1) 파일이 있지만 읽기 전용인 경우

2) 경로 이름이 너무 긴 경우

3) 디스크가 꽉 찬 경우




방법: 텍스트 파일에서 읽기


1. 정적 메서드를 사용 하 여이 예제 텍스트 파일의 내용을 읽어 ReadAllText 및 ReadAllLines 에서 System.IO.File 클래스입니다.

2. StreamReader을 사용하는 예제를 보려면 방법: 텍스트 파일을 한 번에 한 줄씩 읽기(Visual C#)을 참조하십시오.


참고

이 예제에서 사용 되는 파일은 방법: 텍스트 파일에 쓰기(C# 프로그래밍 가이드)에서 만든 파일입니다.


예제

class ReadFromFile
{
    static void Main()
    {
        // The files used in this example are created in the topic
        // How to: Write to a Text File. You can change the path and
        // file name to substitute text files of your own.

        // Example #1
        // Read the file as one string.
        string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

        // Example #2
        // Read each line of the file into a string array. Each element
        // of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }

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




방법: 텍스트 파일을 한 번에 한 줄씩 읽기


1. 이 예제에서는 StreamReader 클래스의 ReadLine 메서드를 사용하여 텍스트 파일의 내용을 한 번에 한 줄씩 문자열로 읽어 들입니다.

2. 각 텍스트 줄은 line 문자열에 저장되고 화면에 표시됩니다.


예제

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = 
    new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
    System.Console.WriteLine (line);
    counter++;
}

file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
System.Console.ReadLine();




방법: 레지스트리에 키 만들기


1. 이 예제에서는 현재 사용자의 레지스트리에 있는 "Names" 키 아래에 "Name"과 "Isabella" 값 쌍을 추가합니다.


Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names");
key.SetValue("Name", "Isabella");
key.Close();


코드 컴파일

1. 코드를 복사한 다음 콘솔 응용 프로그램의 Main 메서드에 붙여넣습니다.

2. Names 매개 변수를 레지스트리의 HKEY_CURRENT_USER 노드 바로 아래에 있는 키 이름으로 바꿉니다.

3. Name 매개 변수를 Names 노드 바로 아래에 있는 값의 이름으로 바꿉니다.

강력한 프로그래밍

1. 키를 넣을 적합한 위치를 찾으려면 레지스트리 구조를 살펴 봅니다.

2. 예를 들어, 현재 사용자의 Software 키를 열고 회사 이름을 갖는 키를 만들 수 있습니다.

3. 그런 다음 해당 레지스트리 값을 회사 키에 추가하면 됩니다.

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

1) 키 이름이 null인 경우

2) 사용자에게 레지스트리 키를 만들 수 있는 권한이 없는 경우

3) 키 이름이 255자 제한을 초과하는 경우

4) 키가 닫힌 경우

5) 레지스트리 키가 읽기 전용인 경우

.NET Framework 보안

1. 데이터를 로컬 컴퓨터(Microsoft.Win32.Registry.LocalMachine)에 쓰는 것보다 사용자 폴더(Microsoft.Win32.Registry.CurrentUser)에 쓰는 것이 더 안전합니다.

2. 레지스트리 값을 만들 때는 해당 값이 이미 존재하는 경우 어떻게 처리할 것인지 결정해야 합니다.

3. 악의적인 프로세스가 이미 해당 값을 만들어 액세스하고 있을 수도 있습니다.

4. 레지스트리 값에 입력한 데이터는 다른 프로세스에서도 사용할 수 있습니다.

5. 이를 방지하려면 Overload:Microsoft.Win32.RegistryKey.GetValue 메서드를 사용합니다.

6. 키가 아직 없으면 이 메서드에서 null을 반환합니다.

7. 레지스트리 키가 ACL(액세스 제어 목록)에 의해 보호되는 경우에도 레지스트리에 암호 등의 비밀을 일반 텍스트로 저장하면 보안상 위험합니다.













'프로그래밍 > C#' 카테고리의 다른 글

C# 코딩 규칙  (0) 2016.08.28
예외 및 예외 처리  (0) 2016.08.26
형식 참조 테이블  (0) 2016.08.23
클래스 및 구조체  (0) 2016.08.05
인터페이스, 이벤트, 인덱서  (0) 2016.08.04
:
Posted by 지훈2