스파르타코딩클럽 게임개발

오늘는 스파르타 코딩 클럽 unity 게임 개발 과정 15일차(팀과제 C# 파일 경로 및 조작 설명)

코드천자문 2023. 11. 18. 00:50
반응형

C#으로 파일 경로 및 파일 조작 이해하기

이번에는 C# 언어를 사용하여 파일 경로를 지정하고 파일을 읽고 쓰는 기본적인 개념에 대해 더 많은 예제와 설명할 것이다.

백슬래시(\)와 점(.)을 포함한 여러 기호를 사용하는 방법, 절대 경로와 상대 경로를 찾는 다양한 방법, 그리고 텍스트파일을 읽고 쓰는 방법을 알아보자.

1. 경로: 절대 vs. 상대

파일 경로를 지정하는 데는 두 가지 주요 유형이 있다. 

  • 절대 경로(Absolute Path): 파일의 전체 경로를 나타낸다.
string absolutePath = @"C:\Users\YourUsername\Documents\file.txt"; // 절대 경로 예제
  • 상대 경로(Relative Path): 현재 작업 중인 디렉토리를 기준으로 상대적인 위치를 나타낸다.
string relativePath = "./file.txt"; // 상대 경로 예제

1.1 경로 지정에 사용되는 기호

경로 지정에 사용되는 몇 가지 기호들이 있습니다.

  • . (점): 현재 디렉토리를 나타낸다.
  • .. (점 두 개): 상위 디렉토리를 나타낸다.
  • / (슬래시): 디렉토리를 구분한다.

예제:

string currentDirectory = "."; // 현재 디렉토리
string parentDirectory = ".."; // 상위 디렉토리
string subDirectory = "./images"; // 현재 디렉토리의 하위 images 디렉토리

 

2. 텍스트 파일 읽고 쓰기

 

2.1 텍스트 파일 읽기

텍스트 파일을 읽는 방법을 다양한 예제와 함께 살펴보자

// 텍스트 파일의 모든 내용 읽기 - 절대 경로 사용
string absolutePathRead = @"C:\Users\YourUsername\Documents\file.txt";
string contentRead = File.ReadAllText(absolutePathRead);
Console.WriteLine(contentRead);

// 텍스트 파일의 모든 내용 읽기 - 상대 경로 사용
string relativePathRead = "./file.txt";
string contentRelativeRead = File.ReadAllText(relativePathRead);
Console.WriteLine(contentRelativeRead);

// 텍스트 파일의 각 라인 읽기
string[] lines = File.ReadAllLines(absolutePathRead);
foreach (string line in lines)
{
    Console.WriteLine(line);
}

 

2.2 텍스트 파일 쓰기

텍스트 파일에 내용을 쓰는 방법을 더 많은 예제와 함께 살펴보자

// 텍스트 파일에 쓰기 - 절대 경로 사용
string absolutePathWrite = @"C:\Users\YourUsername\Documents\new_file.txt";
File.WriteAllText(absolutePathWrite, "Hello, World!");

// 텍스트 파일에 쓰기 - 상대 경로 사용
string relativePathWrite = "./new_file.txt";
File.WriteAllText(relativePathWrite, "Hello, World!");

// 텍스트 파일에 내용 추가하기
File.AppendAllText(absolutePathWrite, "\nAppended Text!");

 

3. 팀과제

 

3.1 팀과제에 적용한 모습

private void StartScreenText()
{
    /*
    . (점): 현재 디렉토리를 나타냅니다.
    .. (점 두개): 상위 디렉토리를 나타냅니다.
    / (슬래시): 디렉토리를 구분합니다.
    */

    string directory = "../../../StartScreenText.txt"; // 상대 경로를 사용한 파일 경로
    try
    {
        string[] fileContents = File.ReadAllLines(directory, Encoding.UTF8);

        // 파일 내용 출력
        foreach (string line in fileContents)
        {
            foreach (char cha in line)
            {
                Console.Write(cha);
                if (!Console.KeyAvailable) Thread.Sleep(50);
            }
            Console.WriteLine();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"파일을 읽는 도중 오류 발생: {ex.Message}");
    }
}

팀 프로젝트에서 캐릭터 생성전 이야기를 들려주는데 그 텍스트파일을 불러오는 코드다.

 

3.2 시행착오

처음에는 도대체 경로지정에 사용하는 기호를 몰라 메서드를 만들어서 이런식으로 막 짜버렸다.

return Directory.GetParent(Directory.GetParent(Directory.GetParent(directoryInfo).ToString()).ToString()).ToString();

 

상단의 코드와 하단의 코드는 같은 역할을 한다는것이 .. 믿어지지 않는다.

 string directory = "../../../StartScreenText.txt";

 

 

오늘 배운것.

상대경로와 절대경로를 이용하여 파일의 위치를 찾을 수 있고 읽을 수 있다.

반응형