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)
13321정성태4/14/20233734개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233739개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234179개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20233989개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234145오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233472오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233667Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233743개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233835개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233819Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234311C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20233879C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234034.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20233923스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233719.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233567Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20233902Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234261VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233564Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234181Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234319Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20233949Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233735Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233675Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234348Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233691Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...