본문 바로가기
카테고리 없음

[VB.NET] 파일 저장 시 유효하지 않은 파일명에 대한 특수 문자 처리 및 복구 방법

by IT HUB 2024. 4. 17.
728x90
반응형
 
Public Function StringToFileName(fName As String) As String
    Dim V() As String = {"%", "\", "/", ":", "*", "?", """", "<", ">", "|"} '// 변환시
     Dim str As String = fName
     For Each T As String In V
          Dim s As String = CStr(Asc(T))
          If s.Length < 3 Then
               s = "0" & s
               s = String.Format("%{0}", Microsoft.VisualBasic.Right(s, 2))
          Else
               s = "0" & s
               s = Microsoft.VisualBasic.Right(s, 4)
               s = String.Format("%{0}%{1}", s.Substring(0, 2), s.Substring(2, 2))
          End If
          str = Replace$(str, T, s)
     Next
     Return str
End Function
Public Function FileNameToString(fName As String) As String
     Dim V() As String = {"\", "/", ":", "*", "?", """", "<", ">", "|", "%"} '// 복구시
     Dim str As String = fName
     For Each T As String In V
          Dim s As String = CStr(Asc(T))
          If s.Length < 3 Then
               s = "0" & s
               s = String.Format("%{0}", Microsoft.VisualBasic.Right(s, 2))
          Else
               s = "0" & s
               s = Microsoft.VisualBasic.Right(s, 4)
               s = String.Format("%{0}%{1}", s.Substring(0, 2), s.Substring(2, 2))
          End If
          str = Replace$(str, s, T)
     Next
     Return str
End Function

파일명을 안전하게 저장하고, 추후에 원본 파일명을 정확하게 복구할 수 있는 VB.NET 함수를 작성해 보겠습니다. 이를 위해 금지된 문자를 유니코드 값으로 변환하고, 특정 접두사를 사용하여 이러한 치환을 식별할 수 있게 합니다. 이 방식은 복구가 가능하며, 충돌을 방지합니다.

파일명 치환 함수

Public Function ReplaceInvalidFileNameChars(fileName As StringAs String 
    Dim invalidChars As Char() = System.IO.Path.GetInvalidFileNameChars()
    Dim safeFileName As New System.Text.StringBuilder(fileName) 
 
    For Each c As Char In invalidChars 
        safeFileName.Replace(c, "_U" + AscW(c).ToString("X4")) 
    Next 
 
    Return safeFileName.ToString() 
End Function

파일명 복구 함수

Public Function RecoverFileName(safeFileName As StringAs String
    Dim recoveredFileName As New System.Text.StringBuilder(safeFileName)
 
    ' 순차적으로 Unicode 포인트에 해당하는 문자를 복구합니다.
    Dim regex As New System.Text.RegularExpressions.Regex("_U([0-9A-F]{4})")
    Dim m As System.Text.RegularExpressions.Match = regex.Match(safeFileName)
 
    While m.Success
        Dim unicodeChar As Char = ChrW(Convert.ToInt32(m.Groups(1).Value, 16))
        recoveredFileName.Replace(m.Value, unicodeChar)
        m = m.NextMatch()
    End While
 
    Return recoveredFileName.ToString()
End Function

사용법 및 설명

  • 치환 함수 (ReplaceInvalidFileNameChars): 파일 이름에 포함된 모든 유효하지 않은 문자를 해당 유니코드 값으로 치환합니다. 예를 들어, \_U005C로 변환됩니다.
  • 복구 함수 (RecoverFileName): 치환된 문자열을 검사하여 _UXXXX 형식을 갖는 모든 문자를 원래의 문자로 복구합니다. 여기서 XXXX는 문자의 유니코드 포인트입니다.

이 방식을 사용하면, 파일 이름에 원래 _UXXXX 형식의 문자열이 포함되어 있더라도 이를 올바르게 처리할 수 있습니다. 단, 파일 이름에 _U와 네 자리 숫자가 자연스럽게 포함되는 경우에도 이를 원래 문자로 잘못 복구할 수 있는 위험이 있으므로, 이 점을 유의하여 사용해야 합니다. 가능하다면, 사용 환경에서 _UXXXX 패턴이 자연스럽게 발생할 가능성이 낮은지 확인해야 합니다.

반응형

댓글