How do I use OpenFileDialog to select a folder? - c#

I was going to use the following project: https://github.com/scottwis/OpenFileOrFolderDialog
However, there's a problem: it uses the GetOpenFileName function and OPENFILENAME structure. OPENFILENAME has the member named templateID, which is the identifier for dialog template. And the project contains the res1.rc file and the templated dialog init, too. But I couldn't figure out how to attach this file to my C# project.
Is there a better way to use an OpenFileDialog to select folders?

Basically you need the FolderBrowserDialog class:
Prompts the user to select a folder. This class cannot be inherited.
Example:
using(var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
string[] files = Directory.GetFiles(fbd.SelectedPath);
System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
If you work in WPF you have to add the reference to System.Windows.Forms.
you also have to add using System.IO for Directory class

As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.
This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)
Install-Package Microsoft.WindowsAPICodePack-Shell
For the include line:
using Microsoft.WindowsAPICodePack.Dialogs;
Usage:
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
MessageBox.Show("You selected: " + dialog.FileName);
}

There is a hackish solution using OpenFileDialog where ValidateNames and CheckFileExists are both set to false and FileName is given a mock value to indicate that a directory is selected.
I say hack because it is confusing to users about how to select a folder. They need to be in the desired folder and then just press Open while file name says "Folder Selection."
This is based on Select file or folder from the same dialog by Denis Stankovski.
OpenFileDialog folderBrowser = new OpenFileDialog();
// Set validate names and check file exists to false otherwise windows will
// not let you select "Folder Selection."
folderBrowser.ValidateNames = false;
folderBrowser.CheckFileExists = false;
folderBrowser.CheckPathExists = true;
// Always default to Folder Selection.
folderBrowser.FileName = "Folder Selection.";
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
string folderPath = Path.GetDirectoryName(folderBrowser.FileName);
// ...
}

Here is a pure C# version, nuget-free, that should work with all versions of .NET (including .NET Core, .NET 5, WPF, Winforms, etc.) and uses Windows Vista (and higher) IFileDialog interface with the FOS_PICKFOLDERS options so it has the nice folder picker Windows standard UI.
I have also added WPF's Window type support but this is optional, the WPF-marked lines can just be removed.
usage:
var dlg = new FolderPicker();
dlg.InputPath = #"c:\windows\system32";
if (dlg.ShowDialog() == true)
{
MessageBox.Show(dlg.ResultPath);
}
code:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Windows; // for WPF support
using System.Windows.Interop; // for WPF support
public class FolderPicker
{
public virtual string ResultPath { get; protected set; }
public virtual string ResultName { get; protected set; }
public virtual string InputPath { get; set; }
public virtual bool ForceFileSystem { get; set; }
public virtual string Title { get; set; }
public virtual string OkButtonLabel { get; set; }
public virtual string FileNameLabel { get; set; }
protected virtual int SetOptions(int options)
{
if (ForceFileSystem)
{
options |= (int)FOS.FOS_FORCEFILESYSTEM;
}
return options;
}
// for WPF support
public bool? ShowDialog(Window owner = null, bool throwOnError = false)
{
owner ??= Application.Current.MainWindow;
return ShowDialog(owner != null ? new WindowInteropHelper(owner).Handle : IntPtr.Zero, throwOnError);
}
// for all .NET
public virtual bool? ShowDialog(IntPtr owner, bool throwOnError = false)
{
var dialog = (IFileOpenDialog)new FileOpenDialog();
if (!string.IsNullOrEmpty(InputPath))
{
if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out var item), throwOnError) != 0)
return null;
dialog.SetFolder(item);
}
var options = FOS.FOS_PICKFOLDERS;
options = (FOS)SetOptions((int)options);
dialog.SetOptions(options);
if (Title != null)
{
dialog.SetTitle(Title);
}
if (OkButtonLabel != null)
{
dialog.SetOkButtonLabel(OkButtonLabel);
}
if (FileNameLabel != null)
{
dialog.SetFileName(FileNameLabel);
}
if (owner == IntPtr.Zero)
{
owner = Process.GetCurrentProcess().MainWindowHandle;
if (owner == IntPtr.Zero)
{
owner = GetDesktopWindow();
}
}
var hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED)
return null;
if (CheckHr(hr, throwOnError) != 0)
return null;
if (CheckHr(dialog.GetResult(out var result), throwOnError) != 0)
return null;
if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var path), throwOnError) != 0)
return null;
ResultPath = path;
if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out path), false) == 0)
{
ResultName = path;
}
return true;
}
private static int CheckHr(int hr, bool throwOnError)
{
if (hr != 0)
{
if (throwOnError)
Marshal.ThrowExceptionForHR(hr);
}
return hr;
}
[DllImport("shell32")]
private static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem ppv);
[DllImport("user32")]
private static extern IntPtr GetDesktopWindow();
#pragma warning disable IDE1006 // Naming Styles
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
#pragma warning restore IDE1006 // Naming Styles
[ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] // CLSID_FileOpenDialog
private class FileOpenDialog
{
}
[ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog
{
[PreserveSig] int Show(IntPtr parent); // IModalWindow
[PreserveSig] int SetFileTypes(); // not fully defined
[PreserveSig] int SetFileTypeIndex(int iFileType);
[PreserveSig] int GetFileTypeIndex(out int piFileType);
[PreserveSig] int Advise(); // not fully defined
[PreserveSig] int Unadvise();
[PreserveSig] int SetOptions(FOS fos);
[PreserveSig] int GetOptions(out FOS pfos);
[PreserveSig] int SetDefaultFolder(IShellItem psi);
[PreserveSig] int SetFolder(IShellItem psi);
[PreserveSig] int GetFolder(out IShellItem ppsi);
[PreserveSig] int GetCurrentSelection(out IShellItem ppsi);
[PreserveSig] int SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
[PreserveSig] int GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[PreserveSig] int SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[PreserveSig] int SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
[PreserveSig] int SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[PreserveSig] int GetResult(out IShellItem ppsi);
[PreserveSig] int AddPlace(IShellItem psi, int alignment);
[PreserveSig] int SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[PreserveSig] int Close(int hr);
[PreserveSig] int SetClientGuid(); // not fully defined
[PreserveSig] int ClearClientData();
[PreserveSig] int SetFilter([MarshalAs(UnmanagedType.IUnknown)] object pFilter);
[PreserveSig] int GetResults([MarshalAs(UnmanagedType.IUnknown)] out object ppenum);
[PreserveSig] int GetSelectedItems([MarshalAs(UnmanagedType.IUnknown)] out object ppsai);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
[PreserveSig] int BindToHandler(); // not fully defined
[PreserveSig] int GetParent(); // not fully defined
[PreserveSig] int GetDisplayName(SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
[PreserveSig] int GetAttributes(); // not fully defined
[PreserveSig] int Compare(); // not fully defined
}
#pragma warning disable CA1712 // Do not prefix enum values with type name
private enum SIGDN : uint
{
SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
SIGDN_FILESYSPATH = 0x80058000,
SIGDN_NORMALDISPLAY = 0,
SIGDN_PARENTRELATIVE = 0x80080001,
SIGDN_PARENTRELATIVEEDITING = 0x80031001,
SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001,
SIGDN_PARENTRELATIVEPARSING = 0x80018001,
SIGDN_URL = 0x80068000
}
[Flags]
private enum FOS
{
FOS_OVERWRITEPROMPT = 0x2,
FOS_STRICTFILETYPES = 0x4,
FOS_NOCHANGEDIR = 0x8,
FOS_PICKFOLDERS = 0x20,
FOS_FORCEFILESYSTEM = 0x40,
FOS_ALLNONSTORAGEITEMS = 0x80,
FOS_NOVALIDATE = 0x100,
FOS_ALLOWMULTISELECT = 0x200,
FOS_PATHMUSTEXIST = 0x800,
FOS_FILEMUSTEXIST = 0x1000,
FOS_CREATEPROMPT = 0x2000,
FOS_SHAREAWARE = 0x4000,
FOS_NOREADONLYRETURN = 0x8000,
FOS_NOTESTFILECREATE = 0x10000,
FOS_HIDEMRUPLACES = 0x20000,
FOS_HIDEPINNEDPLACES = 0x40000,
FOS_NODEREFERENCELINKS = 0x100000,
FOS_OKBUTTONNEEDSINTERACTION = 0x200000,
FOS_DONTADDTORECENT = 0x2000000,
FOS_FORCESHOWHIDDEN = 0x10000000,
FOS_DEFAULTNOMINIMODE = 0x20000000,
FOS_FORCEPREVIEWPANEON = 0x40000000,
FOS_SUPPORTSTREAMABLEITEMS = unchecked((int)0x80000000)
}
#pragma warning restore CA1712 // Do not prefix enum values with type name
}
result:

Strange that so much answers/votes, but no one add the following code as an answer:
using (var opnDlg = new OpenFileDialog()) //ANY dialog
{
//opnDlg.Filter = "Png Files (*.png)|*.png";
//opnDlg.Filter = "Excel Files (*.xls, *.xlsx)|*.xls;*.xlsx|CSV Files (*.csv)|*.csv"
if (opnDlg.ShowDialog() == DialogResult.OK)
{
//opnDlg.SelectedPath -- your result
}
}

Sounds to me like you're just after the FolderBrowserDialog.

Here is another solution, that has all the source available in a single, simple ZIP file.
It presents the OpenFileDialog with additional windows flags that makes it work like the Windows 7+ Folder Selection dialog.
Per the website, it is public domain: "There’s no license as such as you are free to take and do with the code what you will."
Article: .NET Win 7-style folder select dialog (http://www.lyquidity.com/devblog/?p=136)
Source code: http://s3downloads.lyquidity.com/FolderSelectDialog/FolderSelectDialog.zip
Archive.org links:
Article: https://web.archive.org/web/20180823181552/http://www.lyquidity.com/devblog/?p=136
Source code: https://web.archive.org/web/20180823181632/http://s3downloads.lyquidity.com/FolderSelectDialog/FolderSelectDialog.zip

Take a look at the Ookii Dialogs libraries which has an implementation of a folder browser dialog for Windows Forms and WPF respectively.
Ookii.Dialogs.WinForms
https://github.com/augustoproiete/ookii-dialogs-winforms
Ookii.Dialogs.Wpf
https://github.com/augustoproiete/ookii-dialogs-wpf

Im new to C# and came across this thread just now.
This might be of interest to those that are new to the language as well.
Change design of FolderBrowserDialog

The answer given by Simon Mourier would be the best answer considering the OP question. It does not involve NuGET package so there will not be any dependency issue in the future for selecting folder method.
If you encountered error related to "...is not available in C# 7.3", just add <LangVersion>8.0</LangVersion> to your .csproj (testing with Visual Studio does not produce any error when build and run)
If you can't change the project language then just replace owner
??= Application.Current.MainWindow
with
owner = owner ?? Application.Current.MainWindow

This is how I use the folder browser dialog in Small Visual Basic. This code solves the non-selected initial folder issue and also selects the folder from the clipboard or the registry (if any), and if the folder is deleted, it goes up through parents until selecting an existing folder. This makes using the dialog very comfortable.
Note that I am sending 4 tabs because I show the Create new folder button, but if you hide it, use two tabs only.
Public Shared Function OpenFolderDialog(initialFolder As String) As String
Dim folder = GetInitialFolder(initialFolder)
If folder = "" Then folder = GetInitialFolder(System.Windows.Clipboard.GetText())
If folder = "" Then folder = GetInitialFolder(GetSetting("sVB", "OpenFolder", "LastFolder", ""))
Dim th As New Threading.Thread(
Sub()
Threading.Thread.Sleep(300)
System.Windows.Forms.SendKeys.SendWait("{TAB}{TAB}{TAB}{TAB}{RIGHT}")
End Sub)
th.Start()
Try
Dim dlg As New System.Windows.Forms.FolderBrowserDialog With {
.Description = "Select a folder:",
.SelectedPath = folder
}
If dlg.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
SaveSetting("sVB", "OpenFolder", "LastFolder", dlg.SelectedPath)
OpenFolderDialog = dlg.SelectedPath
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
Private Shared Function GetInitialFolder(folder As String) As String
Try
If folder <> "" Then
If IO.File.Exists(folder) Then
folder = Path.GetDirectoryName(folder)
Else
Do
If Directory.GetDirectoryRoot(folder) = folder OrElse Directory.Exists(folder) Then
Exit Do
End If
folder = Path.GetDirectoryName(folder)
Loop
End If
End If
Catch
folder = ""
End Try
Return folder
End Function

this should be the most obvious and straight forward way
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if(result == System.Windows.Forms.DialogResult.OK)
{
selectedFolder = dialog.SelectedPath;
}
}

Related

c# IDsObjectPickerCredentials fail

I have to set credentials to Active-Directory-Object-Picker (IDsObjectPicker) on c#.
But I can't force the IDsObjectPickerCredentials to work.
I've made same on c++ (msdn example) and it works good.
I used "headers" from here ComInterop.cs and StructsFlags.cs
Please tell me what I'm doing wrong. How to call IDsObjectPickerCredentials.SetCredentials
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Tulpep.ActiveDirectoryObjectPicker;
namespace cred
{
class Program
{
static void Main(string[] args)
{
string szTargetComputer = #"10.0.9.115";
string szUser = #"TST\test";
string szPassword = #"123qazWSX";
DSObjectPicker picker = new DSObjectPicker();
IDsObjectPicker ipicker = (IDsObjectPicker)picker;
int res = InitObjectPicker(ipicker, szTargetComputer);
if (res == (int)HRESULT.S_OK)
{
try
{
// !!! HERE !!!
IDsObjectPickerCredentials cred = (ipicker as IDsObjectPickerCredentials);
res = cred.SetCredentials(szUser, szPassword);
// c++ like variant
// res = InitCredentials(ipicker, szUser, szPassword);
if (res != (int)HRESULT.S_OK) Console.WriteLine("SetCredentials Fail : 0x{0}", res.ToString("X4")); // On Win32 I get 0x80070057 - looks like E_INVALIDARG
IntPtr hwndParent = Process.GetCurrentProcess().MainWindowHandle;
IDataObject dataObj = null;
int hresult = ipicker.InvokeDialog(hwndParent, out dataObj);
Console.WriteLine(hresult == (int)HRESULT.S_OK ? "OK" : "Cancel");
Console.ReadKey();
}
finally
{
Marshal.ReleaseComObject(ipicker);
}
}
}
[ComImport, Guid("E2D3EC9B-D041-445A-8F16-4748DE8FB1CF"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDsObjectPickerCredentials
{
[PreserveSig()]
int SetCredentials(
[In, MarshalAs(UnmanagedType.LPWStr)] string szUserName,
[In, MarshalAs(UnmanagedType.LPWStr)] string szPassword);
}
static int InitObjectPicker(IDsObjectPicker ipicker, string szTargetComputer)
{
int res = (int)HRESULT.S_FALSE;
DSOP_SCOPE_INIT_INFO[] aScopeInit = new DSOP_SCOPE_INIT_INFO[1];
DSOP_INIT_INFO InitInfo = new DSOP_INIT_INFO();
aScopeInit[0].cbSize = (uint)Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO));
aScopeInit[0].flType =
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN;
aScopeInit[0].FilterFlags.Uplevel.flBothModes =
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_COMPUTERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_USERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_BUILTIN_GROUPS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_INCLUDE_ADVANCED_VIEW;
aScopeInit[0].FilterFlags.flDownlevel =
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_COMPUTERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_USERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_BUILTIN_GROUPS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_INCLUDE_ADVANCED_VIEW;
IntPtr refScopeInitInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO)) * aScopeInit.Length);
try
{
// Marshal structs to pointers
for (int index = 0; index < aScopeInit.Length; index++)
{
Marshal.StructureToPtr(aScopeInit[index], (IntPtr)((int)refScopeInitInfo + index * Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO))), false);
}
InitInfo.cbSize = (uint)Marshal.SizeOf(typeof(DSOP_INIT_INFO));
InitInfo.cDsScopeInfos = (uint)aScopeInit.Length; //sizeof(aScopeInit)/sizeof(DSOP_SCOPE_INIT_INFO);
InitInfo.aDsScopeInfos = refScopeInitInfo;
InitInfo.flOptions = DSOP_INIT_INFO_FLAGS.DSOP_FLAG_MULTISELECT;
InitInfo.pwzTargetComputer = szTargetComputer;
res = ipicker.Initialize(ref InitInfo);
}
finally
{
Marshal.FreeHGlobal(refScopeInitInfo);
}
return res;
}
static int InitCredentials(IDsObjectPicker ipicker, string User, string Password)
{
IntPtr ptr = IntPtr.Zero;
Guid IID_IDsObjectPickerCredentials = new Guid("E2D3EC9B-D041-445A-8F16-4748DE8FB1CF");
IntPtr pIUnk = Marshal.GetIUnknownForObject(ipicker);
int hr = Marshal.QueryInterface(pIUnk, ref IID_IDsObjectPickerCredentials, out ptr);
if (hr == HRESULT.S_OK)
{
try
{
IDsObjectPickerCredentials cred = (IDsObjectPickerCredentials)Marshal.GetObjectForIUnknown(ptr);
hr = cred.SetCredentials(User, Password);
if (hr != HRESULT.S_OK)
{
System.Diagnostics.Debugger.Break(); // Fail
return (int)HRESULT.S_FALSE;
}
}
catch (Exception ex)
{
return (int)HRESULT.S_FALSE;
}
finally
{
Marshal.Release(ptr);
}
}
return (int)HRESULT.S_OK;
}
}
}
The IDsObjectPickerCredentials interface derives from the IDsObjectPicker. Your sample actually calls the Initialize method with a username and a password instead of SetCredentials.
Here is a correct declaration:
[ComImport, Guid("e2d3ec9b-d041-445a-8f16-4748de8fb1cf"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IDsObjectPickerCredentials
{
[PreserveSig]
int Initialize(ref DSOP_INIT_INFO pInitInfo);
[PreserveSig]
int InvokeDialog(IntPtr HWND, out IDataObject lpDataObject);
[PreserveSig]
int SetCredentials(string userName, string password);
}
Please note that instead of deriving from the IDsObjectPicker, the code replicates its methods, in the same order. This is necessary for .NET COM Interop.
You don't need that manual QueryInterface/Release calls, var cred = (IDsObjectPickerCredentials)iobjectpicker; is enough.
Also I found that the SetCredentials should be called before the Initialize method.

Get List of available Verbs (file association) to use with ProcessStartInfo in c#

I am trying to open and print files with the ProcessStartInfo class. (File can be anything but let`s assume it is a PDF File)
ProcessStartInfo pi = new ProcessStartInfo(file);
pi.Arguments = Path.GetFileName(file);
pi.WorkingDirectory = Path.GetDirectoryName(file);
pi.Verb = "OPEN";
Process.Start(pi);
this works well for the pi.Verb = "OPEN";. Some applications register themselves also with the verb "PRINT" but only some do. In my case (Windows PDF Viewer) I get an exception when trying to execute with the pi.Verb = "PRINT";
Is there a way to see all the verbs available for a specific type in C# at runtime?
Thx a lot
The ProcessStartInfo.Verbs property is somewhat broken as it does not consider the way how newer versions of Windows (Windows 8 and above afaik) retrieve the registered application. The property only checks the verbs that are registered for the ProgId defined under HKCR\.ext (as can be seen in the reference source) and does not consider other places such as below the Registry key HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ext or some other places, e.g. defined via Policy.
Getting the registered verbs
The best way is to not rely on checking the Registry directly (as done by the ProcessStartInfo class), but to use the appropriate Windows API function AssocQueryString to retrieve the associated ProgId:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
class Program
{
private static void Main(string[] args)
{
string fileName = #"E:\Pictures\Sample.jpg";
string progId = AssocQueryString(AssocStr.ASSOCSTR_PROGID, fileName);
var verbs = GetVerbsByProgId(progId);
if (!verbs.Contains("printto"))
{
throw new Exception("PrintTo is not supported!");
}
}
private static string[] GetVerbsByProgId(string progId)
{
var verbs = new List<string>();
if (!string.IsNullOrEmpty(progId))
{
using (var key = Registry.ClassesRoot.OpenSubKey(progId + "\\shell"))
{
if (key != null)
{
var names = key.GetSubKeyNames();
verbs.AddRange(
names.Where(
name =>
string.Compare(
name,
"new",
StringComparison.OrdinalIgnoreCase)
!= 0));
}
}
}
return verbs.ToArray();
}
private static string AssocQueryString(AssocStr association, string extension)
{
uint length = 0;
uint ret = AssocQueryString(
AssocF.ASSOCF_NONE, association, extension, "printto", null, ref length);
if (ret != 1) //expected S_FALSE
{
throw new Win32Exception();
}
var sb = new StringBuilder((int)length);
ret = AssocQueryString(
AssocF.ASSOCF_NONE, association, extension, null, sb, ref length);
if (ret != 0) //expected S_OK
{
throw new Win32Exception();
}
return sb.ToString();
}
[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint AssocQueryString(
AssocF flags,
AssocStr str,
string pszAssoc,
string pszExtra,
[Out] StringBuilder pszOut,
ref uint pcchOut);
[Flags]
private enum AssocF : uint
{
ASSOCF_NONE = 0x00000000,
ASSOCF_INIT_NOREMAPCLSID = 0x00000001,
ASSOCF_INIT_BYEXENAME = 0x00000002,
ASSOCF_OPEN_BYEXENAME = 0x00000002,
ASSOCF_INIT_DEFAULTTOSTAR = 0x00000004,
ASSOCF_INIT_DEFAULTTOFOLDER = 0x00000008,
ASSOCF_NOUSERSETTINGS = 0x00000010,
ASSOCF_NOTRUNCATE = 0x00000020,
ASSOCF_VERIFY = 0x00000040,
ASSOCF_REMAPRUNDLL = 0x00000080,
ASSOCF_NOFIXUPS = 0x00000100,
ASSOCF_IGNOREBASECLASS = 0x00000200,
ASSOCF_INIT_IGNOREUNKNOWN = 0x00000400,
ASSOCF_INIT_FIXED_PROGID = 0x00000800,
ASSOCF_IS_PROTOCOL = 0x00001000,
ASSOCF_INIT_FOR_FILE = 0x00002000
}
private enum AssocStr
{
ASSOCSTR_COMMAND = 1,
ASSOCSTR_EXECUTABLE,
ASSOCSTR_FRIENDLYDOCNAME,
ASSOCSTR_FRIENDLYAPPNAME,
ASSOCSTR_NOOPEN,
ASSOCSTR_SHELLNEWVALUE,
ASSOCSTR_DDECOMMAND,
ASSOCSTR_DDEIFEXEC,
ASSOCSTR_DDEAPPLICATION,
ASSOCSTR_DDETOPIC,
ASSOCSTR_INFOTIP,
ASSOCSTR_QUICKTIP,
ASSOCSTR_TILEINFO,
ASSOCSTR_CONTENTTYPE,
ASSOCSTR_DEFAULTICON,
ASSOCSTR_SHELLEXTENSION,
ASSOCSTR_DROPTARGET,
ASSOCSTR_DELEGATEEXECUTE,
ASSOCSTR_SUPPORTED_URI_PROTOCOLS,
ASSOCSTR_PROGID,
ASSOCSTR_APPID,
ASSOCSTR_APPPUBLISHER,
ASSOCSTR_APPICONREFERENCE,
ASSOCSTR_MAX
}
}
From MSDN: https://msdn.microsoft.com/en-us/library/65kczb9y(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
startInfo = new ProcessStartInfo(fileName);
if (File.Exists(fileName))
{
i = 0;
foreach (String verb in startInfo.Verbs)
{
// Display the possible verbs.
Console.WriteLine(" {0}. {1}", i.ToString(), verb);
i++;
}
}

How to determine if a normal user is using elevated rights

I am trying to determinate if my program was launched by an Administrator with admin rights or by a normal user with Administrator rights using the following code:
private void Form1_Load(object sender, EventArgs e)
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (isAdmin)
{
ini();
MessageBox.Show("The user is an admin with admin rights");
}
else
{
MessageBox.Show("Error The user is a normal user with admin rights", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Application.Exit();
}
}
But when I test this code using a normal user account with admin rights, it fails, telling me The user is an admin with admin rights.
I am using .Net 3.5 and the code needs to be compatible with Windows Vista and up.
Can anybody give me some idea to solve this, please? Thank you!!!
To clarify a little bit more, another way to see this problem is this: How can I determinate if my program (running with admin rights by the admin) is running inside the standard user account context.
mmm you need to know is if the user connected to that computer has Admin Rights but an user that is part of a domain control ? (active Directory?) not the BuiltIn ones ? please Clarify., take a look to this post https://social.msdn.microsoft.com/Forums/vstudio/en-US/c2166023-fcfc-4c3c-ba8f-200977971c5d/how-to-check-if-given-user-have-admin-rights-in-c
There are more variables to account for, for instance Operating System. Which version of Microsoft Window's are you utilizing? Remember, the User Access Control (UAC) was introduced in a later version, which can impact the code. Another massive impactor will be a Domain Policy which is regulated through Active Directory.
To avoid those constraints, I would do the following:
private static bool IsElevated()
{
var user = WindowsIdentity.GetCurrent();
var role = WindowsPrincipal(user);
if(Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Version.Major > 6)
if(user != null)
if(role.IsInRole(WindowsBuiltInRole.Administrator))
return true;
return false;
}
This was a quick recreation, but you'll want to test the code to ensure it correctly queries the Operating System and User.
I did solved it!!!
Explanation
I realized that what I needed was the session ID (the enviroment) to get somehow the Logged in Username
(owner of the context).
Getting the session Id was really easy:
int session = System.Diagnostics.Process.GetCurrentProcess().SessionId;
By this time, my goal was getting the username linked to this session, then I found this
Get Windows user name from SessionID
Now, with the username I thought it was really easy to check if this username belongs
to an Administrator group. I was wrong. The easiest way that I found requeried to use wmi and pinvoke.
The main problem was, in order to make the queries, I must know the name of the administrators group in the current OS, that is language-dependent.
The solution was this:
http://www.pinvoke.net/default.aspx/advapi32.lookupaccountsid
I tweaked the code, put all pieces together and that was it.
Summarizing, I found the sessionid, found the username linked to session, found the OS Administrators group name, and did some Wmi queries to check if the user is an Administrator.
This solution works fine for me, but I must say that runs slow.
If anybody can improve this code, or if it is useful to anybody else, I left it here.
Just remember to add a reference to System.Management; I used Visual Studio C# Express 2010. The project was a Windows Forms Application.
Happy coding!!!
//Make sure to add a reference to System.Management;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Security.Principal;
using System.Collections;
using System.Runtime.InteropServices;
namespace RealUSer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Getting the session id
int session = System.Diagnostics.Process.GetCurrentProcess().SessionId;
//Getting the username related to the session id
string user = GetUsernameBySessionId(session, false);
try
{
//Cheching if the user belongs to the local admin group using wmi
if (CheckAdminRights(user))
{
MessageBox.Show("The logged in User "+user+" is an Admin");
}
else
{
MessageBox.Show("The logged in User " + user + " is not an Admin");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// This method checks if the context user, belongs to the local administrators group
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public bool CheckAdminRights(string username)
{
bool result = false;
List<string> admins = new List<string>();
//SelectQuery query = new SelectQuery("Select AccountType from Win32_UserAccount where Name=\"" + username + "\"");
SelectQuery query = new SelectQuery("SELECT * FROM win32_group WHERE Name=\"" + getAdministratorGroupName() + "\"");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection OC = searcher.Get();
IEnumerator enumerator = OC.GetEnumerator();
enumerator.MoveNext();
ManagementObject O = (ManagementObject)enumerator.Current;
ManagementObjectCollection adminusers = O.GetRelated("Win32_UserAccount");
foreach (ManagementObject envVar in adminusers)
{
admins.Add(envVar["Name"].ToString());
//Console.WriteLine("Username : {0}", envVar["Name"]);
//foreach (PropertyData pd in envVar.Properties)
// Console.WriteLine(string.Format(" {0,20}: {1}", pd.Name, pd.Value));
}
if (admins.Contains(username))
result = true;
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///This code will find the administrators group name, independent of the OS language using the LookupAccountSid function with the BUILTIN\Administrators sid
#region
const int NO_ERROR = 0;
const int ERROR_INSUFFICIENT_BUFFER = 122;
enum SID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup,
SidTypeDomain,
SidTypeAlias,
SidTypeWellKnownGroup,
SidTypeDeletedAccount,
SidTypeInvalid,
SidTypeUnknown,
SidTypeComputer
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool LookupAccountSid(
string lpSystemName,
[MarshalAs(UnmanagedType.LPArray)] byte[] Sid,
StringBuilder lpName,
ref uint cchName,
StringBuilder ReferencedDomainName,
ref uint cchReferencedDomainName,
out SID_NAME_USE peUse);
public string getAdministratorGroupName()
{
String result = "";
StringBuilder name = new StringBuilder();
uint cchName = (uint)name.Capacity;
StringBuilder referencedDomainName = new StringBuilder();
uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;
SID_NAME_USE sidUse;
// Sid for BUILTIN\Administrators
byte[] Sid = new byte[] { 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2 };
int err = NO_ERROR;
if (!LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
{
err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (err == ERROR_INSUFFICIENT_BUFFER)
{
name.EnsureCapacity((int)cchName);
referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
err = NO_ERROR;
if (!LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
}
}
if (err == 0)
{
result = name.ToString();
}
return result;
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void Form1_Load(object sender, EventArgs e)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///This code will retrieve user name given the session id
#region
[DllImport("Wtsapi32.dll")]
private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out int pBytesReturned);
[DllImport("Wtsapi32.dll")]
private static extern void WTSFreeMemory(IntPtr pointer);
public static string GetUsernameBySessionId(int sessionId, bool prependDomain)
{
IntPtr buffer;
int strLen;
string username = "SYSTEM";
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSUserName, out buffer, out strLen) && strLen > 1)
{
username = Marshal.PtrToStringAnsi(buffer);
WTSFreeMemory(buffer);
if (prependDomain)
{
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSDomainName, out buffer, out strLen) && strLen > 1)
{
username = Marshal.PtrToStringAnsi(buffer) + "\\" + username;
WTSFreeMemory(buffer);
}
}
}
return username;
}
public enum WTS_INFO_CLASS
{
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType
}
#endregion
}
}

Silently print HTML from WPF WebBrowser

I have to silently print HTML document from WebBrowser in WPF. I have done it NOT silently by that code:
mshtml.IHTMLDocument2 doc = WebBrowser1.Document as mshtml.IHTMLDocument2;
doc.execCommand("Print", true, null);
Now I want to skip the print dialog.
Please help.
For silent printing with WPF WebBrowser, below code worked for me:
private void PrintCurrentPage()
{
// document must be loaded for this to work
IOleServiceProvider sp = WebBrowser1.Document as IOleServiceProvider;
if (sp != null)
{
Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");
const int OLECMDID_PRINT = 6;
const int OLECMDEXECOPT_DONTPROMPTUSER = 2;
dynamic wb; // should be of IWebBrowser2 type
sp.QueryService(IID_IWebBrowserApp, IID_IWebBrowser2, out wb);
if (wb != null)
{
// this will send to the default printer
wb.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, null, null);
}
}
}
[ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IOleServiceProvider
{
[PreserveSig]
int QueryService([MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject);
}
Note: answer was inspired by this SO q & a

Get Product Code of installed Msi

I have a C# program where I have to get the product code of an installed msi. I have only the msi name as the input. Can this be done programmatically?
Do the answers to this question help? They want to get the product name, but maybe it works for the product code, too?
EDIT
If you do not have the MSI file itself to access the database (as suggested by the above link to the other question), you may try to search the following registry path for the name of your MSI file:
HKEY_CLASSES_ROOT\Installer\Products\*\SourceList
There are many entries under the Products branch. Each of them is a product key. Every branch should contain the SourceList node, which in turn should contain the value PackageName. That value holds the name of the MSI file.
So what I'd do is:
for each key in Products
{
open SourceList subkey
read PackageName value
if name equals my msi file name
{
return key-name formatted as GUID
}
}
This is the code I used to get the UninstallString of any MSI.
private string GetUninstallString(string msiName)
{
Utility.WriteLog("Entered GetUninstallString(msiName) - Parameters: msiName = " + msiName);
string uninstallString = string.Empty;
try
{
string path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products";
RegistryKey key = Registry.LocalMachine.OpenSubKey(path);
foreach (string tempKeyName in key.GetSubKeyNames())
{
RegistryKey tempKey = key.OpenSubKey(tempKeyName + "\\InstallProperties");
if (tempKey != null)
{
if (string.Equals(Convert.ToString(tempKey.GetValue("DisplayName")), msiName, StringComparison.CurrentCultureIgnoreCase))
{
uninstallString = Convert.ToString(tempKey.GetValue("UninstallString"));
uninstallString = uninstallString.Replace("/I", "/X");
uninstallString = uninstallString.Replace("MsiExec.exe", "").Trim();
uninstallString += " /quiet /qn";
break;
}
}
}
return uninstallString;
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
This will give a result like this:
MsiExec.exe /I{6BB09011-69E1-472F-ACAD-FA0E7DA3E2CE}
From this string, you can take the substring within the braces {}, which will be 6BB09011-69E1-472F-ACAD-FA0E7DA3E2CE. I hope this might be the product code.
There is most fast and simply way - to use WMI with conditional query string.
public string GetProductCode(string productName)
{
string query = string.Format("select * from Win32_Product where Name='{0}'", productName);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject product in searcher.Get())
return product["IdentifyingNumber"].ToString();
}
return null;
}
This code obtains the product code directly from an MSI file. So this allows reading the code without installing the file.
class MsiHandle : SafeHandleMinusOneIsInvalid
{
public MsiHandle()
: base(true)
{ }
protected override bool ReleaseHandle()
{
return NativeMethods.MsiCloseHandle(handle) == 0;
}
}
class NativeMethods
{
const string MsiDll = "Msi.dll";
[DllImport(MsiDll, CharSet = CharSet.Unicode, ExactSpelling = true)]
public extern static uint MsiOpenPackageW(string szPackagePath, out MsiHandle product);
[DllImport(MsiDll, ExactSpelling=true)]
public extern static uint MsiCloseHandle(IntPtr hAny);
[DllImport(MsiDll, CharSet = CharSet.Unicode, ExactSpelling = true)]
static extern uint MsiGetProductPropertyW(MsiHandle hProduct, string szProperty, StringBuilder value, ref int length);
[DllImport(MsiDll, ExactSpelling = true)]
public static extern int MsiSetInternalUI(int value, IntPtr hwnd);
public static uint MsiGetProductProperty(MsiHandle hProduct, string szProperty, out string value)
{
StringBuilder sb = new StringBuilder(1024);
int length = sb.Capacity;
uint err;
value = null;
if(0 == (err = MsiGetProductPropertyW(hProduct, szProperty, sb, ref length)))
{
sb.Length = length;
value = sb.ToString();
return 0;
}
return err;
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
string msiFile = args[0];
NativeMethods.MsiSetInternalUI(2, IntPtr.Zero); // Hide all UI. Without this you get a MSI dialog
MsiHandle msi;
uint err;
if (0 != (err = NativeMethods.MsiOpenPackageW(args[0], out msi)))
{
Console.Error.WriteLine("Can't open MSI, error {0}", err);
return 1;
}
// Strings available in all MSIs
string productCode;
using (msi)
{
if (0 != NativeMethods.MsiGetProductProperty(msi, "ProductCode", out productCode))
throw new InvalidOperationException("Can't obtain product code");
Console.WriteLine(productCode);
return 0;
}
}
}
Full example in Subversion on http://ankhsvn.open.collab.net/svn/ankhsvn/trunk/src/tools/Ankh.Chocolatey/
Use username 'guest' and no password.
private static bool GetUninstallString(string ProductName)
{
try
{
RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
var key = localKey.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall") ??
localKey.OpenSubKey(
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
if (key == null)
return false;
return key.GetSubKeyNames()
.Select(keyName => key.OpenSubKey(keyName))
.Select(subkey => subkey.GetValue("DisplayName") as string)
.Any(displayName => displayName != null && displayName.Contains(ProductName));
}
catch
{
// Log message
return false;
}
}
This is very usefull for search string by productname

Categories