다음을 통해 공유


Path 클래스

파일이나 디렉터리 경로 정보를 포함하는 String 인스턴스에 대한 작업을 수행합니다. 이러한 작업은 플랫폼 간에 호환되는 방식으로 수행됩니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public NotInheritable Class Path
‘사용 방법
정적 클래스의 멤버는 클래스 인스턴스를 사용하지 않고 직접 액세스할 수 있습니다.
[ComVisibleAttribute(true)] 
public static class Path
[ComVisibleAttribute(true)] 
public ref class Path abstract sealed
/** @attribute ComVisibleAttribute(true) */ 
public final class Path
ComVisibleAttribute(true) 
public final class Path

설명

.NET Framework에서는 "\\.\PHYSICALDRIVE0"과 같은 장치 이름인 물리적 디스크에 경로를 통해 직접 액세스할 수 없습니다.

경로는 파일이나 디렉터리의 위치를 제공하는 문자열입니다. 경로가 디스크에 있는 위치를 가리킬 필요는 없습니다. 예를 들어, 메모리나 장치에 있는 위치로 경로를 매핑할 수 있습니다. 경로의 정확한 형식은 현재 플랫폼에 따라 결정됩니다. 예를 들어, 일부 시스템에서 경로는 드라이브나 볼륨 문자로 시작할 수 있지만 다른 시스템에는 이러한 요소가 없습니다. 또한 일부 시스템에서는 파일에 저장된 정보 형식을 나타내는 확장명이 파일 경로에 포함될 수 있습니다. 확장명의 형식은 플랫폼에 따라 다릅니다. 예를 들어, 일부 시스템의 확장명은 세 개의 문자로 제한되지만 그렇지 않은 시스템도 있습니다. 또한 현재 플랫폼에 따라 경로의 요소를 구분하는 데 사용되는 문자 집합과 경로를 지정할 때 사용할 수 없는 문자 집합이 결정됩니다. 이러한 차이점 때문에 Path 클래스의 필드와 Path 클래스의 일부 멤버 동작은 플랫폼에 따라 다릅니다.

경로에는 상대 위치나 절대 위치 정보가 포함될 수 있습니다. 절대 경로는 위치를 완전하게 지정하기 때문에 현재 위치에 관계없이 파일이나 디렉터리를 고유하게 식별할 수 있습니다. 하지만 상대 경로는 일부 위치만 지정합니다. 상대 경로로 지정된 파일을 찾을 경우 현재 위치가 시작 위치로 사용됩니다. 현재 디렉터리를 확인하려면 Directory.GetCurrentDirectory를 호출합니다.

Path 클래스의 멤버는 대부분 파일 시스템과 상호 작동하지 않으며 경로 문자열로 지정된 파일이 존재하는지 여부를 확인하지 않습니다. ChangeExtension처럼 경로 문자열을 한정하는 Path 클래스 멤버는 파일 시스템의 파일 이름에 영향을 미치지 않습니다. 하지만 Path 멤버는 지정된 경로 문자열을 구성하는 문자에 대한 유효성을 검사하여, InvalidPathChars에 정의된 잘못된 문자가 해당 경로 문자열에 포함된 경우 ArgumentException을 throw합니다. 예를 들어, Windows 기반 데스크톱 플랫폼에서는 경로 문자에 따옴표("), 보다 작음(<), 보다 큼(>), 파이프(|), 백스페이스(\b), null(\0) 및 유니코드 문자 16 ~ 18, 20 ~ 25를 사용할 수 없습니다.

Path 클래스의 멤버를 사용하면 확장명이 경로의 일부인지 확인하고, 두 문자열을 한 경로 이름으로 합치는 등의 일반적인 작업을 빠르고 쉽게 수행할 수 있습니다.

Path 클래스의 모든 멤버는 정적이므로 경로 인스턴스 없이도 호출할 수 있습니다.

참고

입력 문자열로 경로를 받아들이는 멤버의 경우 해당 경로는 제대로 구성되어야 합니다. 그렇지 않으면 예외가 발생합니다. 예를 들어, 경로가 정규화된 경로이지만 공백으로 시작하면 클래스의 메서드에서 경로가 트리밍되지 않습니다. 따라서 경로가 잘못되고 예외가 발생합니다. 비슷하게 경로나 경로 조합은 두 번 정규화될 수 없습니다. 예를 들어, "c:\temp c:\windows"는 대부분의 경우에 예외를 발생시킵니다. 경로 문자열이 적용되는 메서드를 사용할 경우 해당 경로가 제대로 구성되었는지 확인해야 합니다.

경로가 적용되는 멤버에서 경로는 파일이나 디렉터리를 참조할 수 있습니다. 또한 지정된 경로는 서버와 공유 이름의 상대 경로나 UNC(Universal Naming Convention) 경로를 나타낼 수 있습니다. 예를 들어, 다음과 같은 경로를 사용할 수 있습니다.

  • C#의 "c:\\MyDir\\MyFile.txt" 또는 Visual Basic의 "c:\MyDir\MyFile.txt"

  • C#의 "c:\\MyDir" 또는 Visual Basic의 "c:\MyDir"

  • C#의 "MyDir\\MySubdir" 또는 Visual Basic의 "MyDir\MySubDir"

  • C#의 "\\\\MyServer\\MyShare" 또는 Visual Basic의 "\\MyServer\MyShare"

이러한 모든 작업은 문자열에서 수행되기 때문에 모든 경우에 결과가 유효한지 확인할 수 있는 것은 아닙니다. 예를 들어, GetExtension 메서드는 전달된 문자열을 구문 분석하여 해당 문자열에서 확장명을 반환합니다. 하지만 확장명이 반환된다고 해서 해당 확장명의 파일이 디스크에 있다는 의미는 아닙니다.

이 클래스를 사용하는 방법에 대한 예제를 보려면 아래 예제 단원을 참조하십시오. 다음 표에서는 일반적인 예 또는 관련된 I/O 작업의 예를 보여 줍니다.

수행 작업

참조 항목

텍스트 파일을 만듭니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에 씁니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에서 읽습니다.

방법: 파일의 텍스트 읽기

파일 확장명을 검색합니다.

GetExtension

파일의 정규화된 경로를 검색합니다.

GetFullPath

경로에서 파일 이름 및 확장명을 검색합니다.

GetFileName

경로에서 파일 이름만 검색합니다.

GetFileNameWithoutExtension

경로에서 디렉터리 이름만 검색합니다.

GetDirectoryName

확장명을 변경합니다.

ChangeExtension

디렉터리가 있는지 여부를 확인합니다.

Exists

파일이 있는지 여부를 확인합니다.

Exists

예제

다음 코드 예제에서는 Path 클래스의 일부 주 멤버를 보여 줍니다.

Imports System
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        Dim path1 As String = "c:\temp\MyTest.txt"
        Dim path2 As String = "c:\temp\MyTest"
        Dim path3 As String = "temp"

        If Path.HasExtension(path1) Then
            Console.WriteLine("{0} has an extension.", path1)
        End If

        If Path.HasExtension(path2) = False Then
            Console.WriteLine("{0} has no extension.", path2)
        End If

        If Path.IsPathRooted(path3) = False Then
            Console.WriteLine("The string {0} contains no root information.", path3)
        End If

        Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3))
        Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath())
        Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName())

        ' This code produces output similar to the following:
        ' c:\temp\MyTest.txt has an extension.
        ' c:\temp\MyTest has no extension.
        ' The string temp contains no root information.
        ' The full path of temp is D:\Documents and Settings\cliffc\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication2\bin\Debug\temp.
        ' D:\Documents and Settings\cliffc\Local Settings\Temp\8\ is the location for temporary files.
        ' D:\Documents and Settings\cliffc\Local Settings\Temp\8\tmp3D.tmp is a file available for use.

    End Sub
End Class
using System;
using System.IO;

class Test 
{
    
    public static void Main() 
    {
        string path1 = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp\MyTest";
        string path3 = @"temp";

        if (Path.HasExtension(path1)) 
        {
            Console.WriteLine("{0} has an extension.", path1);
        }

        if (!Path.HasExtension(path2)) 
        {
            Console.WriteLine("{0} has no extension.", path2);
        }

        if (!Path.IsPathRooted(path3)) 
        {
            Console.WriteLine("The string {0} contains no root information.", path3);
        }

        Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3));
        Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath());
        Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName());

        /* This code produces output similar to the following:
         * c:\temp\MyTest.txt has an extension.
         * c:\temp\MyTest has no extension.
         * The string temp contains no root information.
         * The full path of temp is D:\Documents and Settings\cliffc\My Documents\Visual Studio 2005\Projects\ConsoleApplication2\ConsoleApplication2\bin\Debug\temp.
         * D:\Documents and Settings\cliffc\Local Settings\Temp\8\ is the location for temporary files.
         * D:\Documents and Settings\cliffc\Local Settings\Temp\8\tmp3D.tmp is a file available for use.
         */
    }
}
using namespace System;
using namespace System::IO;
int main()
{
   String^ path1 = "c:\\temp\\MyTest.txt";
   String^ path2 = "c:\\temp\\MyTest";
   String^ path3 = "temp";
   if ( Path::HasExtension( path1 ) )
   {
      Console::WriteLine( "{0} has an extension.", path1 );
   }

   if (  !Path::HasExtension( path2 ) )
   {
      Console::WriteLine( "{0} has no extension.", path2 );
   }

   if (  !Path::IsPathRooted( path3 ) )
   {
      Console::WriteLine( "The string {0} contains no root information.", path3 );
   }

   Console::WriteLine( "The full path of {0} is {1}.", path3, Path::GetFullPath( path3 ) );
   Console::WriteLine( "{0} is the location for temporary files.", Path::GetTempPath() );
   Console::WriteLine( "{0} is a file available for use.", Path::GetTempFileName() );
   Console::WriteLine( "\r\nThe set of invalid characters in a path is:" );
   Console::WriteLine( "(Note that the wildcard characters '*' and '?' are not invalid.):" );
   Collections::IEnumerator^ myEnum = Path::InvalidPathChars->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Char c =  *safe_cast<Char^>(myEnum->Current);
      Console::WriteLine( c );
   }
}
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        String path1 = "c:\\temp\\MyTest.txt";
        String path2 = "c:\\temp\\MyTest";
        String path3 = "temp";

        if (Path.HasExtension(path1)) {
            Console.WriteLine("{0} has an extension.", path1);
        }
        if (!(Path.HasExtension(path2))) {
            Console.WriteLine("{0} has no extension.", path2);
        }
        if (!(Path.IsPathRooted(path3))) {
            Console.WriteLine("The string {0} contains no root information.",
                path3);
        }

        Console.WriteLine("The full path of {0} is {1}.", path3, 
            Path.GetFullPath(path3));
        Console.WriteLine("{0} is the location for temporary files.",
            Path.GetTempPath());
        Console.WriteLine("{0} is a file available for use.", 
            Path.GetTempFileName());
        Console.WriteLine("\r\nThe set of invalid characters in a path is:");
        Console.WriteLine("(Note that the wildcard characters '*' and '?' "
            + "are not invalid.):");
        char c = ' ';
        for (int iCtr = 0; iCtr < Path.InvalidPathChars.get_Length(); iCtr++) {
            c = Path.InvalidPathChars[iCtr];
            Console.WriteLine(c);
        }
    } //main
} //Test

상속 계층 구조

System.Object
  System.IO.Path

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Path 멤버
System.IO 네임스페이스

기타 리소스

파일 및 스트림 I/O
방법: 파일의 텍스트 읽기
방법: 파일에 텍스트 쓰기
기본 파일 I/O
방법: 새로 만든 데이터 파일 읽기 및 쓰기