程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> [C#] 如何選擇一個目錄

[C#] 如何選擇一個目錄

編輯:.NET實例教程
基本思路是利用SHBrowseForFolder 於是有如下代碼:

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();
}


這絕對是最簡便的解決辦法。雖然沒有釋放pidlReturned有可能造成少量內存洩漏,但是那麼一點內存,誰在乎呢?
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved