[C #] How to select a directory

Source: Internet
Author: User
Tags bool
The basic idea is to use the SHBrowseForFolder so as to have the following code:

Private Enum Browseflag
{
Bif_returnonlyfsdirs = 0x0001,//for finding a folder to start document searching
Bif_dontgobelowdomain = 0x0002,//For starting the Find Computer
Bif_statustext = 0x0004,
Bif_returnfsancestors = 0x0008,
Bif_editbox = 0x0010,
Bif_validate = 0x0020,//insist on valid result (or CANCEL)

Bif_browseforcomputer = 0x1000,//browsing for Computers.
Bif_browseforprinter = 0x2000,//browsing for Printers
bif_browseincludefiles= 0x4000//browsing for Everything
}

[StructLayout (LayoutKind.Sequential)]
private struct BROWSEINFO
{
Public IntPtr hWndOwner;
Public IntPtr pidlroot;
[MarshalAs (UNMANAGEDTYPE.LPTSTR)]
public string displayname;
[MarshalAs (UNMANAGEDTYPE.LPTSTR)]
public string title;
public int flags;
Public INTPTR callback;
public INTPTR lparam;
}

[DllImport ("Shell32.dll", CharSet=CharSet.Auto)]
static extern IntPtr SHBrowseForFolder (ref browseinfo info);
[DllImport ("Shell32.dll", CharSet=CharSet.Auto)]
[Return:marshalas (Unmanagedtype.bool)]
internal extern static bool SHGetPathFromIDList (IntPtr pidl, [MarshalAs (UNMANAGEDTYPE.LPTSTR)] System.Text.StringBuilder Pszpath);

public static string Browsefolder (IWin32Window owner)
{
Browseinfo info = new Browseinfo ();
Info.flags = (int) browseflag.bif_returnonlyfsdirs
+ (int) browseflag.bif_statustext
+ (int) browseflag.bif_validate;
Info.hwndowner = owner. Handle;
IntPtr pidlreturned = SHBrowseForFolder (ref info);

StringBuilder sb = new StringBuilder (260);
SHGetPathFromIDList (pidlreturned, SB);

Return SB. ToString ();
}


This is definitely the easiest way to solve the problem. Although no release of pidlreturned may result in a small amount of memory leak, but then a little memory, who cares?




Related Article

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.