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)
13449정성태11/21/20232351개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232627닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232487닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232419닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232699Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232456닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232492개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232322개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232652닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232352Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232844닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232462닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232656닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232893닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232828닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232631스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232357스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232406오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232720스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232612닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232871닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232923닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233101닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233283스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233099닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233078스크립트: 58. 파이썬 - async/await 기본 사용법
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...