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

비밀번호

댓글 작성자
 




... [181]  182  183  184  185  186  187  188  189  190  191  192  193  194  195  ...
NoWriterDateCnt.TitleFile(s)
492정성태5/23/200726596.NET Framework: 89. ManagedThreadId - 두 번째 이야기 [5]파일 다운로드1
491정성태5/21/200726713.NET Framework: 88. ManagedThreadId ? [4]
490정성태5/19/200735212오류 유형: 33. error MSB6003: SxS DLL 로딩 오류 [2]
489정성태5/14/200723045.NET Framework: 87. .NET 2.0에서 C# 3.0 기능 사용하기
488정성태5/14/200721600Windows: 25. Multiple Input Queues
487정성태4/24/200727206VC++: 32. VC++에서 bool이 가지는 의미 [3]
486정성태3/22/200726234Windows: 24. DreamScene과 DWM(Desktop Window Manager)의 관계 [1]
485정성태3/17/200721538오류 유형: 32. VS.NET 2005 - x64 환경에서의 mixed 디버깅 환경 구성
484정성태3/17/200720722오류 유형: 31. SQL Compact Edition 설치 후 오류
483정성태3/17/200742125오류 유형: 30. x64 환경: .NET + COM 프로젝트 실행 시 오류 - 80040154 [2]
482정성태3/17/200731622Team Foundation Server: 17. 팀 프로젝트 접속 및 사용
481정성태3/17/200725536Team Foundation Server: 16. 팀 프로젝트 읽기 전용 사용자 등록
480정성태3/14/200723741.NET Framework: 86. GC(Garbage Collector)의 변화
479정성태3/14/200727603개발 환경 구성: 25. D820 - ReadyBoost 구동
478정성태3/14/200727069개발 환경 구성: 24. D820 고주파음 문제
477정성태3/14/200736347개발 환경 구성: 23. 비스타 x64 버전에서 서명되지 않은 드라이버 사용 [4]
476정성태3/9/200731800개발 환경 구성: 22. D820 노트북 - 설치 및 BitLocker 구성 [1]
475정성태3/6/200726183.NET Framework: 85. 공용 프로퍼티 자동 생성
474정성태3/5/200724413.NET Framework: 84. Lambda 표현식 응용 사례 [1]
473정성태3/4/200731479디버깅 기술: 14. TFS 오류 추적(TF53010, TF14105)
472정성태3/3/200730712디버깅 기술: 13. 예외 발생 시 Minidump 생성 - WinDBG [3]파일 다운로드1
471정성태3/1/200719738디버깅 기술: 12. Managed Method에 Break Point 걸기
469정성태2/28/200731351디버깅 기술: 11. (Managed) Main Method에 Break Point 걸기 [3]파일 다운로드1
470정성태3/1/200722787    답변글 디버깅 기술: 11.1. (Managed) Main Method에 Break Point 걸기 - 내용 보강
468정성태2/25/200732503COM 개체 관련: 20. 탭 브라우저의 윈도우 핸들 구하기 [3]
466정성태2/22/200724321Windows: 23. 롱혼 서버 코어 버전 [2]
... [181]  182  183  184  185  186  187  188  189  190  191  192  193  194  195  ...