컴퓨터(OS)는 대부분의 상황에서 상대경로가 아닌 절대경로로 파일을 읽는다고 한다.
절대경로는 루트(최상단 디렉터리)부터 그 파일이 있는 경로까지 전부 나타낸다.
C:/Users/Username/Documents
일 때, ./folder/file.txt
는 C:/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}");
}
}
}
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()
메서드를 사용하여 파일에 문자열을 쓴다.
절대경로
는 고정된 경로로 파일이나 디렉토리 위치를 완전히 명시
상대경로
는 현재 작업 디렉토리를 기준으로 파일이나 디렉토리의 위치를 상대적으로 지정하며, 유연하게 위치를 변경할 수 있음