Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# - 폴더 경로 문자열에서 "..", "." 표기를 고려한 최종 문자열을 얻는 방법 - 두 번째 이야기

예전에 다음의 글을 쓴 적이 있는데요.

C# - 폴더 경로 문자열에서 "..", "." 표기를 고려한 최종 문자열을 얻는 방법
; https://www.sysnet.pe.kr/2/0/1808

그래서 Path.GetFullPath나 Uri 타입의 LocalPath를 이용하면 ".", ".." 경로를 정규화할 수 있습니다. 그런데, 이게 유닉스 계열의 경로에 대해서는 반환을 잘 하지 못합니다. 가령 다음과 같은 문자열이 있을 때,

string txt = "/home/tester/bin/x64/Debug/../test.conf";

Path.GetFullPath나 Uri 타입을 사용하면 결과가 이렇게 나옵니다.

Path.GetFullPath
    C:\home\tester\bin\x64\test.conf

Uri.LocalPath - 예외 발생
    System.UriFormatException: Invalid URI: The format of the URI could not be determined.
       at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
       at System.Uri..ctor(String uriString)
       ...[생략]...

물론, 위의 결과는 윈도우에서 실행했을 때입니다. Linux에서 실행하면 정상적으로 다음과 같이 정규화된 경로를 얻을 수 있습니다.

Path.GetFullPath
    /home/tester/bin/x64/test.conf

Uri.LocalPath
    /home/tester/bin/x64/test.conf

그래도 가끔은 윈도우 환경에서 리눅스 경로를 함께 다뤄야 할 수도 있는데요. 어쩔 수 없습니다. 이런 경우에는 만들어야지. ^^

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string txt = "/home/tester/bin/x64/Debug/../test.conf";

        NoException(Path.GetFullPath, txt);
        NoException((path) => new Uri(path).LocalPath, txt);
        NoException(NormalizePath, txt);
    }

    private static void NoException(Func<string, string> normalizePath, string path)
    {
        try
        {
            Console.WriteLine(normalizePath(path));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine();
    }

    internal static string NormalizePath(string path)
    {
        List<string> pathList = new List<string>();
        string[] parts = path.Split(new char[] { '/', '\\' }, StringSplitOptions.None);

        foreach (string part in parts)
        {
            if (part == ".")
            {
                continue;
            }

            if (part == ".." && pathList.Count >= 1)
            {
                pathList.RemoveAt(pathList.Count - 1);
                continue;
            }

            pathList.Add(part);
        }

        return string.Join('/'.ToString(), pathList.ToArray());
    }
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/22/2019]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 166  167  168  169  170  171  172  [173]  174  175  176  177  178  179  180  ...
NoWriterDateCnt.TitleFile(s)
680정성태3/21/200925167.NET Framework: 125. WPF - RadioButton에 대한 데이터바인딩(2) [1]파일 다운로드1
679정성태3/15/200920241오류 유형: 72. IE 8 멈춤 현상 - 두 번째 이야기
678정성태3/15/200925379개발 환경 구성: 37. Hyper-V에서 Vista의 Virtual Machine Bus 장치 인식 문제
677정성태3/15/200925850개발 환경 구성: 36. MSI P45 Neo3-FR V2 - RAID 1 구성
997정성태2/26/201121198    답변글 개발 환경 구성: 36.1. 개발 환경 구성: 34 - 1. RAID 1 구성 이후...
676정성태3/15/200922483오류 유형: 71. IE 8 RC1 - 멈춤 현상
675정성태3/14/200925343오류 유형: 70. Virtual Machine Additions 제거
673정성태3/11/200923997웹: 10. 금일 진행되었던 마이크로소프트 IE 8 행사의 ActiveX 세션 PPT [6]파일 다운로드1
672정성태3/1/200937006Windows: 43. Loopback network adapter 설치하기 [2]
670정성태2/22/200930193.NET Framework: 124. IIS 7에서 SVC 호스팅 [1]
669정성태2/21/200924534오류 유형: 69. The SQL Server Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service.
668정성태2/21/200929696개발 환경 구성: 35. SQL Express 버전과 User Instance 옵션
667정성태2/14/200941626웹: 9. IE 7. IWebBrowser2 인터페이스 메서드의 Navigate / Navigate2 차이점 [3]파일 다운로드1
666정성태2/12/200927468웹: 8. IE 8: 프로세스와 윈도우의 관계 - LCIE [1]파일 다운로드1
665정성태2/7/200924403웹: 7. Internet Explorer 8 - XHR, XDR, XST, XSRF [1]
664정성태2/5/200920418Windows: 42. Concurrency Runtime
663정성태2/5/200925042.NET Framework: 123. WPF - Arial Narrow 폰트 문제
662정성태2/3/200920711VS.NET IDE: 59. HyperAddin 도구 사용 설명 [1]
661정성태2/3/200924420오류 유형: 68. msxml6r.dll 설치 오류
660정성태2/3/200923071Windows: 41. UAC 보안 취약 [2]
659정성태2/2/200934375오류 유형: 67. ClickOnce 응용 프로그램이 실행되지 않을 때.
658정성태2/1/200926430Team Foundation Server: 30. 소스 서버 보안
657정성태2/1/200929319Windows: 40. Q1 Ultra + Windows 7 베타
656정성태2/1/200930809디버깅 기술: 24. .NET JIT 최적화 코드 생성 제어
655정성태1/31/200927120Windows: 39. IE8 표준 모드 [4]
653정성태1/29/200922021.NET Framework: 122. XML Serializer를 이용한 값 복사: 성능은 어떨까!파일 다운로드1
... 166  167  168  169  170  171  172  [173]  174  175  176  177  178  179  180  ...