HOWTO · Csharp

C#의 파일 이름에서 잘못된 문자 제거

C#의 파일 이름에서 잘못된 문자를 제거하는 방법에 대한 작은 가이드입니다.

이 페이지의 내용

이 문서는 C#을 사용하여 경로에서 파일 이름을 가져오는 방법에 대한 간단한 자습서입니다. 또한 파일 이름에서 잘못된 문자를 제거하는 방법에 대해 설명합니다.

C#에서 파일 이름 가져오기

C# 라이브러리에서 제공되는 일부 메서드는 전체 경로에서 파일 이름을 추출하는 데 사용됩니다. 전체 경로에는 드라이브 이름, 폴더 이름 계층 및 확장자가 있는 실제 파일 이름이 포함될 수 있습니다.

많은 상황에서 경로의 파일 이름이 필요할 수 있습니다. 따라서 C#의 Path 클래스에서 GetFileName() 메서드를 사용하여 파일 이름을 추출할 수 있습니다.

C#GetFileName() 함수

getFileName() 함수의 구문은 다음과 같습니다.

public static string GetFileName(string completePath);

completePath가 파일 이름을 추출해야 하는 전체 경로가 포함된 문자열인 경우 이 함수는 string 변수의 확장명과 함께 파일 이름을 반환합니다.

GetFileName()의 작동 예를 살펴보겠습니다.

using System;
using System.IO;
using System.Text;

namespace mynamespace {

  class FileNameExample {
    static void Main(string[] args) {
      string stringPath = "C:// files//textFiles//myfile1.txt";

      string filename = Path.GetFileName(stringPath);
      Console.WriteLine("Filename = " + filename);
      Console.ReadLine();
    }
  }
}

출력:

Filename = myfile1.txt

C#의 파일 이름에서 잘못된 문자 제거

위에서 언급한 함수는 파일 이름에 일부 잘못된 문자가 있는 경우 ArgumentException을 제공할 수 있습니다. 이러한 잘못된 문자는 GetInvalidPathChars()GetInvalidFilenameChars() 함수에 정의되어 있습니다.

다음 정규식과 Replace 기능을 사용하여 파일 이름에서 유효하지 않거나 잘못된 문자를 제거할 수 있습니다.

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace mynamespace {

  class FileNameExample {
    static void Main(string[] args) {
      string invalidFilename = "\"M\"\\y/Ne/ w**Fi:>> l\\/:*?\"| eN*a|m|| e\"ee.?";
      string regSearch =
          new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
      Regex rg = new Regex(string.Format("[{0}]", Regex.Escape(regSearch)));
      invalidFilename = rg.Replace(invalidFilename, "");
      Console.WriteLine(invalidFilename);
    }
  }
}

출력:

MyNe wFi l eNam eee.

위의 코드 조각에서 두 함수(예: GetInvalidPathChars()GetInvalidFilenameChars())의 잘못된 문자를 연결하고 결과의 정규식을 만들었습니다.

그런 다음 지정된 파일 이름(여러 개의 잘못된 문자 포함)에서 모든 잘못된 문자를 검색하고 Replace 기능을 사용하여 공백으로 바꿨습니다.