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)
13297정성태3/26/20234350Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233692Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20233957Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234126.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234194오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234314Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234719.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234223.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233419Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233517Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233687Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234147Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233739Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20233939Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233481오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233819Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233720Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234469개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234012오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20233970개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234587개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234315.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234669.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234260.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20233957.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234215오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...