[C#] 상대경로와 절대경로

임수정·2024년 7월 3일
0

📝 Learning Log

목록 보기
23/47
post-thumbnail

컴퓨터(OS)는 대부분의 상황에서 상대경로가 아닌 절대경로로 파일을 읽는다고 한다.
절대경로는 루트(최상단 디렉터리)부터 그 파일이 있는 경로까지 전부 나타낸다.

📍 상대경로(Relative Path)

  • 상대경로는 현재 작업 디렉토리를 기준으로 파일의 위치를 나타낸다.
  • 예를 들어, 현재 작업 디렉토리가 C:/Users/Username/Documents일 때, ./folder/file.txtC:/Users/Username/Documents/folder/file.txt를 의미합니다.
  • '.'은 현재 디렉토리를 나타내며, '../'는 상위 디렉토리를 나타낸다. 예를 들어, '../folder/file.txt는 현재 디렉토리의 상위 디렉토리의 'folder' 디렉토리에 있는 'file.txt'를 의미

📖 상대경로를 이용한 파일 읽기

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string relativePath = "./folder/file.txt";
        string fullPath = Path.Combine(Environment.CurrentDirectory, relativePath);

        try
        {
            string content = File.ReadAllText(fullPath);
            Console.WriteLine($"File content: {content}");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"File not found: {fullPath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Path.Combine(Environment.CurrentDirectory, relativePath)를 사용하여 상대경로를 절대경로로 변환

📖 상대경로를 이용한 파일 쓰기

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string relativePath = "./folder/new_file.txt";
        string fullPath = Path.Combine(Environment.CurrentDirectory, relativePath);

        try
        {
            string contentToWrite = "Hello, World!";
            File.WriteAllText(fullPath, contentToWrite);
            Console.WriteLine($"File '{fullPath}' written successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

📍 절대경로(Absolute Path)

  • 절대경로는 파일의 전체 경로를 나타낸다.
  • 예를 들어, C:/Users/Username/Documents/file.txt와 같이 파일이나 디렉토리의 정확한 위치를 명시
  • 절대경로는 작업 디렉토리에 관계없이 항상 동일한 파일을 참조할 수 있다.

📖 절대경로를 이용한 파일 읽기

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string absolutePath = @"C:\Users\Username\Documents\file.txt";

        try
        {
            string content = File.ReadAllText(absolutePath);
            Console.WriteLine($"File content: {content}");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"File not found: {absolutePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

File.ReadAllText() 메서드를 사용하여 파일의 내용을 읽어온다.

📖 절대경로를 이용한 파일 쓰기

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string absolutePath = @"C:\Users\Username\Documents\new_file.txt";

        try
        {
            string contentToWrite = "Hello, World!";
            File.WriteAllText(absolutePath, contentToWrite);
            Console.WriteLine($"File '{absolutePath}' written successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

File.WriteAllText() 메서드를 사용하여 파일에 문자열을 쓴다.

📍 요약

절대경로고정된 경로로 파일이나 디렉토리 위치를 완전히 명시
상대경로현재 작업 디렉토리를 기준으로 파일이나 디렉토리의 위치를 상대적으로 지정하며, 유연하게 위치를 변경할 수 있음

profile
언어는 거들 뿐...

0개의 댓글