Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법

관련해서 질문이 올라왔습니다. ^^

EXE파일에 속성값 추가하는 방법이 있나요?
; https://www.sysnet.pe.kr/3/0/5680

질문하신 분은 속성 창의 "Details" 패널에,

custom_prop_1.png

사용자 정의 칼럼을 추가하고 싶은 듯한데요, (아마도 방법이 있을 것 같은데) 아쉽게도 관련 문서를 찾지를 못하겠습니다. ^^; 예전에는 이와 관련해서 자료가 많았는데, 어느 순간부터 Azure와 닷넷 위주로 자료들이 개편되면서 과거 C/C++로 만들었던 Explorer 확장과 관련한 문서들을 쉽게 찾을 수 없는 상황이 되었습니다.

일단, "Details" 패널에 보이진 않더라도 사용자 정의 칼럼을 추가하는 것은 가능합니다. 이에 대해서는 다음의 글에서 자세하게 설명하고 있는데요,

The Complete Idiot's Guide to Writing Shell Extensions - Part VIII
 - A tutorial on adding columns to Explorer's details view via a column handler shell extension.
; https://www.codeproject.com/Articles/722/The-Complete-Idiots-Guide-to-Writing-Shell-Exten-8

이렇게 해서 추가한 칼럼은 아래 화면과 같이,

custom_prop_2.gif

Explorer의 칼럼을 표시하는 헤더 영역을 마우스 우 클릭해 "More ..." 메뉴를 선택하는 것으로, 파일 탐색기의 리스트 뷰에서 보이게 할 수는 있습니다. (하지만 속성 창의 "Details" 패널에는 보이지 않습니다.)

대신, 저것을 꼭 속성 창에서 보고 싶다면 "Details"가 아닌 별도의 탭 페이지를 추가하는 식으로 구현할 수는 있습니다. 역시 이에 대해서도 다음의 문서에서 자세하게 설명하고 있습니다.

The Complete Idiot's Guide to Writing Shell Extensions - Part V
 - A tutorial on writing a shell extension that adds pages to the properties dialog of files.
; https://www.codeproject.com/Articles/463/The-Complete-Idiots-Guide-to-Writing-Shell-Exten-5

그럼, 자신이 추가한 키/값을 보여주는 탭을 아래와 같은 식으로 자유자재로 추가하는 것이 가능합니다.

custom_prop_3.png




C# 코드에서 사용자 정의 칼럼을 추가하는 방법 중의 하나는 DSOFile 구성요소를 활용하는 것입니다.

DSOFile
; https://www.nuget.org/packages/DSOFile/

64 Bit Application Cannot Use DSOfile
; https://www.codeproject.com/Tips/1118708/Bit-Application-Cannot-Use-DSOfile

C# Add and Edit Office Document Custom Properties
; https://scatteredcode.net/c-add-and-edit-ntfs-custom-properties

아쉽게도 현재 dsofile 패키지는 deprecated 상태라서 "Install-Package" 명령어로 설치가 안 되므로, 직접 dsofilenupkg.1.0.0.nupkg 패키지를 다운로드해,

dsofilenupkg.1.0.0.nupkg
; https://www.nuget.org/api/v2/package/dsoFileNuPKG/1.0.0

압축을 풀어 나온 dsofile.dll을 regsvr32로 등록한 다음,

C:\Lib> dir
 Volume in drive C has no label.
 Volume Serial Number is C00B-0E7F

 Directory of C:\Lib

2022-06-13  오전 10:21    <DIR>          .
2022-06-13  오전 09:56           242,176 dsofile.dll
               1 File(s)        242,176 bytes
               1 Dir(s)  673,986,424,832 bytes free

C:\Lib> regsvr32 dsofile.dll

비주얼 스튜디오의 COM 참조 탭을 이용해 "DSO OLE Document Properties Reader 2.0" 구성 요소를 추가해야 합니다. (참고로 manifest 파일을 이용하면 배포 시 등록 과정은 생략할 수 있습니다.)

이후, 다음과 같이 원하는 파일에 대해 사용자 정의 속성 값을 추가/설정할 수 있습니다.

using System;
using System.Linq;

// 주의 사항: dsofile은 deprecated 패키지이므로 보안상 문제가 발생할 수 있습니다.

internal class Program
{
    static void Main(string[] args)
    {
        DSOFile.OleDocumentPropertiesClass file = new DSOFile.OleDocumentPropertiesClass();

        file.Open(@"test.txt", false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);

        string key = "key1";
        object value = "value3";

        if (file.CustomProperties.Exists(key) == false)
        {
            // Adds new custom property.
            file.CustomProperties.Add(key, ref value);
        }
        else
        {
            file.CustomProperties[key].set_Value(ref value);
        }

        // Go through existing custom properties.
        foreach (DSOFile.CustomProperty p in file.CustomProperties)
        {
            Console.WriteLine("{0}:{1}", p.Name, p.get_Value().ToString());
        }

        file.Save();

        file.Close(true);
    }
}

static class External
{
    internal static bool Exists(this DSOFile.CustomProperties props, string key)
    {
        foreach (DSOFile.CustomProperty p in props)
        {
            if (p.Name == key)
            {
                return true;
            }
        }

        return false;
    }
}

위의 코드는 단순히 ADS(Alternate Data Stream)에 독자적인 유형의 "key1" 데이터를 쓴 것에 불과합니다. 실제로 sysinternals의 streams와 같은 도구를 이용해 다음과 같이 확인할 수 있습니다.

C:\temp\ConsoleApp2\bin\Debug> streams test.txt

streams v1.60 - Reveal NTFS alternate streams.
Copyright (C) 2005-2016 Mark Russinovich
Sysinternals - www.sysinternals.com

C:\temp\ConsoleApp2\bin\Debug\test.txt: 
   :DocumentSummaryInformation:$DATA   212
   :{4c8cc155-6c1e-11d1-8e41-00c04fb9386d}:$DATA        0

당연히, 이렇게 추가한 속성은 코드로만 접근할 수 있을 뿐 "The Complete Idiot's Guide to Writing Shell Extensions - Part VIII" 글에서 다룬 것처럼 탐색기의 헤더 칼럼과는 연동되지 않습니다.

어찌 보면... 저렇게 ads로만 기록하는 용도라면 굳이 dsofile을 이용하기보다는 ADS 읽기/쓰기를 직접 수행하는 것이 더 편리할 것입니다.




만약 임의의 파일이 아닌, OLE Document에 한해 속성을 쓰는 것이라면 Microsoft.WindowsAPICodePack 패키지를 활용하는 것도 좋습니다.

Install-Package Microsoft.WindowsAPICodePack-Shell
Install-Package Microsoft.WindowsAPICodePack-Core

using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

// Read/Write 'Extended' file properties (C#)
// https://stackoverflow.com/questions/220097/read-write-extended-file-properties-c
namespace ConsoleApp3
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"test.docx";
            var file = ShellFile.FromFilePath(filePath);

            // Read and Write:

            string[] oldAuthors = file.Properties.System.Author.Value;
            string oldTitle = file.Properties.System.Title.Value;

            file.Properties.System.Author.Value = new string[] { "Author #1", "Author #2" };
            file.Properties.System.Title.Value = "Example Title";
            file.Properties.System.Comment.Value = "test is good";

            // Alternate way to Write:

            ShellPropertyWriter propertyWriter = file.Properties.GetPropertyWriter();
            propertyWriter.WriteProperty(SystemProperties.System.FileVersion, new string[] { "1.0.0.5 " });
            // propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
            propertyWriter.Close();
        }
    }
}

또는, OpenXml에 해당하는 Office 문서로 한정한다면 DocumentFormat.OpenXml 패키지를 이용하는 것도 고려할 수 있습니다.

Install-Package DocumentFormat.OpenXml 

using System;
using DocumentFormat.OpenXml.Packaging;

namespace GetApplicationProperty
{
    // Install-Package DocumentFormat.OpenXml 
    class Program
    {
        private const string FILENAME =
            @"C:\temp\test.docx";

        static void Main(string[] args)
        {
            using (WordprocessingDocument document =
                WordprocessingDocument.Open(FILENAME, true))
            {
                var props = document.ExtendedFilePropertiesPart.Properties;
                props.Company = new DocumentFormat.OpenXml.ExtendedProperties.Company("test_cmp");
                props.Save();
            }

            using (WordprocessingDocument document =
                WordprocessingDocument.Open(FILENAME, false))
            {
                var props = document.ExtendedFilePropertiesPart.Properties;

                if (props.Company != null)
                    Console.WriteLine("Company = " + props.Company.Text);

                if (props.Lines != null)
                    Console.WriteLine("Lines = " + props.Lines.Text);

                if (props.Manager != null)
                    Console.WriteLine("Manager = " + props.Manager.Text);
            }
        }
    }
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/13/2022]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13375정성태6/20/20232988스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233120오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234404오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233114개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233134개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233301개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233101개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233230개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233347오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233137.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232913오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233698.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233265스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233175.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233639오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233037오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233355오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233667.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233776DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233710.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233973.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233591.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234093VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233345오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233684.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...