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)
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232178디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20232822닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232294오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232307Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232317Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232500Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232546닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232262개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232232Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232345개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232133개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232067오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232381개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232194개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232161개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232297닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232818닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232267개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232603개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232299개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232481닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232206닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232278닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...