How to use C # Shell32.dll

Source: Internet
Author: User

1 to use Shell32 First, add a shell32.dll reference to the project reference (note: The reference is a system DLL file that can be copied to the project in the C:\Windows\System32 directory)

  private void btnTest_Click (object sender, EventArgs e)//Test button click event {//test to import student in Excel into SQL Server db_mes if  Data table does not exist then create System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog (); The new an Open File dialog box is used to select the file if (FD. ShowDialog () = = DialogResult.OK) {string filePath = fd. filename;//instantiates a Shell object Shell32.shell shell = new Shell32.shellclass ();//Gets the file where the parent directory object is, folder folder = Shell. NameSpace (filepath.substring (0, filepath.lastindexof (' \ \)));//Gets the file corresponding to the FolderItem object FolderItem item = folder. ParseName (filepath.substring (filepath.lastindexof (' \ \ ') + 1));//dictionary holds the key-value relationship of the property name and the property value to Dictionary<string, string> Properties = new dictionary<string, string> (); int i = 0;while (true) {//Gets the property name string key = folder. Getdetailsof (null, i), if (string. IsNullOrEmpty (key)) {//When no attribute is desirable, a loop break is introduced;} Gets the property value of String value = folder.   Getdetailsof (item, I);//Save Property Properties.add (key, value), This.richTextBox1.Text + = i.tostring () + key + ":" + value + ' \ n '; All property values are displayed on the RichTextBox control created on the form interface i++;}}

  

------My open file name is 1.xls---------the actual running effect is as follows------can see the index of the information we need according to the result of the operation

0 Name: 1.XLS1 Size: 16.0 KB2 Project type: Microsoft Office Excel 97-2003 worksheet 3 Date Modified: 2017/12/22 11:354 Date Created: 2017/12/22 10:385 access date: 2017/12 /22 11:356 Properties: A7 Offline Status: 8 offline Availability: 9 hypothetical type: Document 10 owner: User-20170822cm\administrator11 Kind: Document 12 date taken: 13 artists involved in the creation: 14 albums: 15:16 Genres : 17 Conductors: 18 Tags: 19 rating: Unrated 20 Author: Administrator21 title: 22 Subject: 23 Category: 24 Note: 25 Copyright: 26#:27 Length: 28 bit rate: 29 Protection: 30 Camera Model: 31 Size: 32 camera Manufacturer: 33 Company : 34 File Description: 35 program Name: 36 Duration: 37 Online: 38 Repeat: 39 Position: 40 Optional participant address: 41 Optional Attendees: 42 organizer Address: 43 Organizer Name: 44 Reminder Time: 45 Required attendee Address: 46 Required Attendee: 47 resource: 48 Meeting status : 49 Free Busy Status: 50 Total size: 51 account Name: 52 Task Status: 53 Computer: user-20170822cm (native) 54 anniversary: 55 Assistant Name: 56 Assistant Tel: 57 Birthday: 58 Business Address: 59 Company City: 60 Company's country/region : 61 Company Email: 62 The location of the company's ZIP code: 63 The company's provinces and municipalities: 64 The street Address: 65 Business Fax: 66 Company Home: 67 Business Phone: 68 Call Number: 69 Car Phone: 70 children: 71 Company Main Tel: 72 Department: 73 e-mail address : 74 Email 2:75 email 3:76 e-mail list: 77 e-Mail Display name: 78 File: 79 Name: 80 full Name: 81 Sex: 82:83 Hobby: 84 Residential Address: 85 Residential City: 86 residential Country: 87 Residential Mailbox : 88 residential Area ZIP code: 89 residential Provinces and municipalities: 90 Residential street Address: 91 Residential Fax: 92 Home Tel: 93 Address: 94 Initials: 95 Title: 96 Tags: 97 surname: 98 Mailing Address: 99 Middle Name: 100 Mobile: 101 Nickname : 102 Office Location: 103 Other addresses: 104 Other cities: 105 Other Countries: 106 Other P.O. Boxes: 107 Other postal codes: 108 Other provinces and municipalities: 109 Other Streets Address: 110 Pager: 111 appellation: 112 City: 113 Country: 114 Mailbox : 115 ZIP Code: 116 Provinces and municipalities: 117 streetsAddress: 118 Main Email: 119 Main Tel: 120 Occupation: 121 Spouse/PARTNER: 122 suffix: 123TTY/TTD Tel: 124telex:125 page: 126 content Status: 127 content Type: 128 Get Date: 129 Archive Date: 130 finish date : 131 Device Category: 132 Connected: 133 Discovery Method: 134 Friendly Name: 135 Local computer: 136 Manufacturer: 137 Model: 138 Paired: 139 Category: 140 Printer Status: 141 client id:142 Contributor: 143 Time to create content : 144 Last Print time: 145 Date Last saved:? 2017/?12/?22?? 11:35,146 Division: 147 Document id:148 page range: 149 slides: 150 editor-in-chief time: 151 words: 152 deadline: 153 End Date: 154 file count: 155 file Name: 1.xls156 file version: 157 flag color: 158 Flag Status : 159 free Space: 160 bit Depth: 161 Horizontal Resolution: 162 width: 163 Vertical resolution: 164 Height: 165 importance: 166 is attachment: 167 deleted: 168 encryption Status: 169 marked: 170 Completed: 171 Incomplete: 172 reading Status: 173 shared : No 174 written by: 175 Date: 176 folder name: Desktop 177 folder path: c: \ user \administrator\ Desktop 178 folder-Desktop (c + + user \administrator) 179 participants: 180 path: \ n user \ Administrator\ Desktop \1.xls181 by location: 182 type: Microsoft Office Excel 97-2003 worksheet 183 Contact: 184 Item Type: 185 Language: 186 access time: 187 Description: 188 Link Status: Unresolved 189 link target: 190url:191 Create media Date: 192 release date: 193 Code personnel: 194 Producer: 195 Publisher: 196 Subtitle: 197 User Web url:198 Creator: 199 attachments: 200 bcc address: 201 bcc : 202 CC Address: 203 cc: 204 session id:205 Received: 206 Date Sent: 207 from: 208 from: 209 with Attachments: 210 Sender Address: 211 Sender: 212 Storage: 213 recipient address: 214 Action title: 215 recipient : 216 Miles: 217 albums artist: 218 albums id:219 beats per minute: 220 Composer: 221 Initial tuning: 222 part of the compilation: 223 atmosphere: 224 Part setting: 225 Period: 226 color:227 Home Rating: 228 Parent rating Reason: 229 used space: 230EXIF version: 231 event: 232 Exposure Compensation: 233 Exposure Program: 234 exposure Time: 235 aperture value: 236 Flash Mode: 237 focal length: 23835mm focal length: 239ISO speed : 240 lens Manufacturer: 241 Lens Model: 242 light Source: 243 max aperture: 244 Metering Mode: 245 direction: 246 Personnel: 247 Program mode: 248 saturation: 249 target distance: 250 white balance: 251 Priority: 252 Item: 253 channel number: 254 Episode name : 255 closed Subtitles: 256 rerun: 257sap:258 Broadcast Date: 259 program Description: 260 record time: 261 radio call signal: 262 radio station name: 263 Abstract: 264 fragment: 265 auto Rollup: 266 search Level: 267 sensitivity: 268 shared device : 269 shared Status: Private 270 product Name: 271 Product Version: 272 Support Link: 273 Source: 274 Start Date: 275 Billing Information: 276 Complete: 277 Task owner: 278 Total File Size: 279 Legal Trademark: 280 Video Compression: 281 Director: 282 Data Rate : 283 Frame Height: 284 frame rate: 285 frame width: 286 total bit rate:

  

The above method returns all the property values, on my Win7 Pro 64bit, returns 287 properties! As you can imagine, the information is very rich, but the speed is slow enough.

As you can see, the above code uses a loop, which is indexed by I when getting property names and property values. So, can we just use the subscript to get the desired property without passing the loop? The code is as follows:

<summary>////Get specified file specified subscript property value///</summary>//<param name= "FilePath" > File path < /param>//<param name= "index" > attribute subscript </param>//<returns> property value </returns> PU Blic static string Getpropertybyindex (string filePath, int index) {if (! File.exists (FilePath)) {throw new FileNotFoundException ("The specified file does not exist.            ", FilePath);            }//Initialize Shell interface Shell32.shell shell = new Shell32.shellclass (); Gets the file where the parent directory object is folder folder = Shell.            NameSpace (Path.getdirectoryname (FilePath)); Gets the file corresponding to the FolderItem object FolderItem item = folder.            ParseName (Path.getfilename (FilePath));             String value = null; Gets the property name string key = folder.            Getdetailsof (null, index); if (false = = string. IsNullOrEmpty (key)) {//Gets the property value = folder. Getdetailsof (Item,index);        } return value; }

  

In my system environment, the resolution "size" subscript is 31, then I only need Getpropertybyindex (fd.filename,31) to obtain the resolution information. However, it is important to note that the subscript for the "size" attribute is not necessarily the same in different versions of Windows (XP,VISTA,WIN7,WIN2003, etc.).

OK, we also notice that each property has a corresponding "property name", then we can get the property value by the property name, which is more than the use of subscript insurance. The code is as follows:

<summary>////Get the value of the specified property name for a specific file///</summary>//<param name= "FilePath" > File path </        param>//<param name= "PropertyName" > Property names </param>//<returns> property values </returns> public static string GetProperty (String FilePath, String propertyname) {if (! File.exists (FilePath)) {throw new FileNotFoundException ("The specified file does not exist.            ", FilePath);            }//Initialize Shell interface Shell32.shell shell = new Shell32.shellclass (); Gets the file where the parent directory object is folder folder = Shell.            NameSpace (Path.getdirectoryname (FilePath)); Gets the file corresponding to the FolderItem object FolderItem item = folder.            ParseName (Path.getfilename (FilePath));            String value = null;            int i = 0; while (true) {//Gets the property name string key = folder.                Getdetailsof (null, i); if (string.     IsNullOrEmpty (key)) {               Exit loop break when no attributes are desirable; } if (true = = string.                     Equals (Key, PropertyName, Stringcomparison.currentcultureignorecase)) {//Get property value Value = folder.                    Getdetailsof (item, i);                Break            } i++;        } return value; }getproperty

  

This method was written by me at the beginning, by adding the property name to the while, until the corresponding property name is found, the corresponding property value is returned.

But this method is still not concise, "size" attribute at 31, meaning that each time need to loop 31 times to get the value I want, if I want to get the property name labeled 287 (see above), then the number will be more, so I have some code to optimize:

<summary>////store property names with their subscripts (key values are lowercase)////</summary> private static dictionary<string,         Int> _propertyindex = null; <summary>////Get the value of the specified property name for a specific file///</summary>//<param name= "FilePath" > File path </        param>//<param name= "PropertyName" > Property names </param>//<returns> property values </returns> public static string Getpropertyex (String FilePath, String propertyname) {if (_propertyindex = = NULL            ) {Initpropertyindex ();            }//Convert to lowercase string propertynamelow = Propertyname.tolower ();                if (_propertyindex.containskey (Propertynamelow)) {int index = _propertyindex[propertynamelow];            Return Getpropertybyindex (FilePath, index);        } return null; }///<summary>///Initialize the subscript for the property name///</summary> Private static void Initpropertyindex () {dictionary<string, int> propertyindex = new Dictionary<strin            G, int> (); Get the file where this code is located as a temporary file for getting the property list string tempfile = System.Reflection.Assembly.GetExecutingAssembly ().            FullName;            dictionary<string, string> allproperty = GetProperties (tempfile);                if (allproperty! = null) {int index = 0; foreach (var item in Allproperty.keys) {//property name is converted uniformly to lowercase and used for ignoring case _proper Tyindex.add (item.                    ToLower (), index);                index++;        }} _propertyindex = Propertyindex; }getpropertyex

  

Propertyindex is used to store property names and their subscripts, with dictionary because the time complexity of _propertyindex[key] is O (1). The subscript of the property name is then found in the Getpropertyex method, and the property value of the subscript is returned directly. The Initpropertyindex method is only called once.

OK, now that we get the property value by property name, shouldn't there be a problem between the different systems?

Not necessarily, the reason you certainly also thought, if is in an English windows, its attribute name inside does not have "the size", corresponding should be "Resolution" and so on (I do not have the English version system, therefore only guesses), also does not have "the name" the attribute, but "the names";

To summarize,

Method name

Apply

Not applicable

Getpropertybyindex

Systems in different languages

Different versions of the system

Getpropertyex

Different versions of the system

Systems in different languages

So, depending on the possible operating environment of your program, choose the method that is right for you;

Rethinking: What if you want to be able to use different versions of the system in different languages?

How to use C # Shell32.dll

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.