Inhibit Input Validation on CommonOpenFileDialog in Win API Pack - c#

This is a WPF app with the latest version of the .NET framework and VS2015
on a Win 10 box.
I am trying to use the "CommonOpenFileDialog" from the Windows API code pack 1.1
to allow the user to establish a folder in which to do some stuff. The folder
can be either an existing folder, or a new one that the user specifies.
If the user wants to create a new folder, then I want them to be able to specify
the folder by editing the text within the "Folder:" textbox at the bottom of the
dialog. Within this context, the dialog would just be a means by which to
navigate to the folder in which the new one is to be created. My plan is to
validate the input within my code to check for a valid (existing) path, and
simply create the path if it does not exist.
Here is the code:
private void test1_folderSelectorDialog ()
{
if (CommonFileDialog.IsPlatformSupported)
{
var folderSelectorDialog = new CommonOpenFileDialog();
folderSelectorDialog.EnsureReadOnly = false;
folderSelectorDialog.IsFolderPicker = true;
folderSelectorDialog.Multiselect = false;
folderSelectorDialog.EnsureValidNames = false;
folderSelectorDialog.EnsurePathExists = false;
folderSelectorDialog.EnsureFileExists = false;
folderSelectorDialog.InitialDirectory
= "C:\\My_Initial_Directory";
folderSelectorDialog.Title = "test1_folderSelectorDialog";
if (folderSelectorDialog.ShowDialog() == CommonFileDialogResult.Ok)
TxBx_folder.Text = folderSelectorDialog.FileName;
this.Focus();
}
else
MessageBox.Show ("CommonFileDialog is not supported");
}
When I run the dialog and modify the text within the "Folder:" textbox,
then press "Select Folder", the dialog validates the input and issues a
dialog popup with the message:
"Path does not exist. Check the path and try again."
Please note that I have set "EnsureValidNames", "EnsurePathExists", and
"EnsureFileExists" to "false". (If they do not control dialog validation,
then what are they there for?)
I can right-click on the dialog window and use "new > Folder" to create a
new folder (which is what I'll have to do if I cannot resolve this issue),
but I'd rather do it the way that I am trying to do it, as it seems much
easier and more intuitive to do it that way.
How do I get the silly thing to shaddup and just accept the input without
passing judgement upon it?
Thanks!

If you want the user to select only the folder, then below code is enough
CommonOpenFileDialog dialog = new CommonOpenFileDialog()
dialog.IsFolderPicker = true
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
filesPath = dialog.FileName
}
I believe below things are not required
folderSelectorDialog.Multiselect = false
folderSelectorDialog.EnsureValidNames = false
folderSelectorDialog.EnsurePathExists = false
folderSelectorDialog.EnsureFileExists = false

Related

Microsoft.WindowsAPICodePack.Dialogs see files when IsFolderPicker = true; [duplicate]

I am using Microsoft's CommonOpenFileDialog to allow users to select a Folder, but no files are visible when the dialog comes up. Is it possible to show files as well as folders when IsFolderPicker is set to true?
My current code looks like this
var dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
SelectedFolderPath = dialog.FileName;
}
Off the top of my head, this is how I did it
var dialog = new CommonOpenFileDialog
{
EnsurePathExists = true,
EnsureFileExists = false,
AllowNonFileSystemItems = false,
DefaultFileName = "Select Folder",
Title = "Select The Folder To Process"
};
dialog.SetOpenButtonText("Select Folder");
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
dirToProcess = Directory.Exists(dialog.FileName) ? dialog.FileName : Path.GetDirectoryName(dialog.FileName);
EDIT: Holy 2 years ago Batman!
Seems like few changes were made, snippet below seems to do the job
var openFolder = new CommonOpenFileDialog();
openFolder.AllowNonFileSystemItems = true;
openFolder.Multiselect = true;
openFolder.IsFolderPicker = true;
openFolder.Title = "Select folders with jpg files";
if (openFolder.ShowDialog() != CommonFileDialogResult.Ok)
{
MessageBox.Show("No Folder selected");
return;
}
// get all the directories in selected dirctory
var dirs = openFolder.FileNames.ToArray();
Not very sure if it even possible to do in a standard way, but even considering that yes, think about UI. Seeing contemporary folders and files in one place, but be able to select only folders, doesn't seem to me a good UI. IMHO it's better, and more "natural" way, to have one control populated with folders, and another (clearly readonly) populated with only files that have to be loaded.
Hope this helps.
If you want the user to select a folder only, have you considered using a FolderBrowserDialog?

C# SaveFileDialog come out warning when using "System" user to running the WinForm

When using a WinForm to click a button. and call save filDialog will come out
"C:\Windows\system32\config\systemprofile\Desktop".
http://i.stack.imgur.com/wH7J9.jpg
The challancing is this software must be runing in the "System" user.
But I using the SaveFileDialog for saving a file. will comes out the message like "C:\Windows\system32\config\systemprofile\Desktop".
I guess the problem is that when I using "system" user, the default user profile is no exist and counld no find the "Destop" floder path.
Because it will not have the "user profile" # "system" user.
This error comes out at I click the button, this application try to init the SaveFileDialog and also try genarate the icon shortcut on the left hand side so cause the error.
The dropdownbox also have the save problem.
http://i.stack.imgur.com/5Hy3S.jpg
Could any one know how to remove the icon shourt cut at the left hand side and the dropdown box icon also have the same problem.
using (var dialog = new SaveFileDialog())
{
dialog.DefaultExt = "txt";
dialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "test";
dialog.AutoUpgradeEnabled = false;
dialog.InitialDirectory = Application.StartupPath;
try
{
DialogResult result = dialog.ShowDialog(this);
if (result == DialogResult.OK)
{
//do something
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
I just using very very very simple code.
ps. I am using C#.net 4.0 , vs2010 running at win2008r2 and win 7
Thanks all !!!
Try setting the InitialDirectory property of the SaveFileDialog
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = "c:\\yourDirectory";
You can also use this method to check if the my documents directory exists on disk.
Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

creating notify icon in system tray and adding shortcut to startup using .net setup creation wizard

I have searched a lot but still not able to find the right solution.
I want to create a setup using .net setup wizard and add 2 checkbox in the setup wizard.
1st checkbox will ask user to "add program in startup". If it is checked then it will add software to startup.
2nd checkbox will ask for "create system tray notify icon". If checked then it will create a notify icon in system tray. The notify icon must be displayed permanently not only when application runs).
I know it had to do with custom actions but still not able to figure it out. Please provide me some article or code for this with proper explanation.
Actually, the custom actions is the right place to do this. Here's the code I use to create two custom checkboxes during the installation process.
[RunInstaller(true)]
public class DeploymentManager : Installer{
public override void Install(IDictionary stateSaver) {
base.Install (stateSaver);
const string DESKTOP_SHORTCUT_PARAM = "DESKTOP_SHORTCUT";
const string QUICKLAUNCH_SHORTCUT_PARAM = "QUICKLAUNCH_SHORTCUT";
const string ALLUSERS_PARAM = "ALLUSERS";
// The installer will pass the ALLUSERS, DESKTOP_SHORTCUT and QUICKLAUNCH_SHORTCUT
// parameters. These have been set to the values of radio buttons and checkboxes from the
// MSI user interface.
// ALLUSERS is set according to whether the user chooses to install for all users (="1")
// or just for themselves (="").
// If the user checked the checkbox to install one of the shortcuts, then the corresponding
// parameter value is "1". If the user did not check the checkbox to install one of the
// desktop shortcut, then the corresponding parameter value is an empty string.
bool allusers = true; // Context.Parameters[ALLUSERS_PARAM] != string.Empty;
bool installDesktopShortcut = true; //Context.Parameters[DESKTOP_SHORTCUT_PARAM] != string.Empty;
bool installQuickLaunchShortcut = true;// Context.Parameters[QUICKLAUNCH_SHORTCUT_PARAM] != string.Empty;
if (installDesktopShortcut){
// If this is an All Users install then we need to install the desktop shortcut for
// all users. .Net does not give us access to the All Users Desktop special folder,
// but we can get this using the Windows Scripting Host.
string desktopFolder = null;
if (allusers){
try{
// This is in a Try block in case AllUsersDesktop is not supported
object allUsersDesktop = "AllUsersDesktop";
WshShell shell = new WshShellClass();
desktopFolder = shell.SpecialFolders.Item(ref allUsersDesktop).ToString();
}
catch {}
}
if (desktopFolder == null)
desktopFolder = Environment.GetFolderPathEnvironment.SpecialFolder.DesktopDirectory);
CreateShortcut(desktopFolder, ShortcutName, Path.Combine(TargetAssemblyFolder, TargetAssembly), ShortcutDescription, Path.Combine(TargetAssemblyFolder, "your.ico"));
}
if (installQuickLaunchShortcut){
CreateShortcut(QuickLaunchFolder, ShortcutName, ShortcutFullName, ShortcutDescription, Path.Combine(TargetAssemblyFolder, "your.ico"));
}
}
private void CreateShortcut(string folder, string name, string target, string description, string targetIcon){
string shortcutFullName = Path.Combine(folder, name + ".lnk");
try{
WshShell shell = new WshShellClass();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(shortcutFullName);
link.TargetPath = target;
link.Description = description;
FileInfo fi = new FileInfo(targetIcon);
link.IconLocation = Path.Combine(fi.Directory.FullName, fi.Name);
link.Save();
}catch (Exception ex){
MessageBox.Show(string.Format("The shortcut \"{0}\" could not be created.\n\n{1}", shortcutFullName, ex.ToString()),
"Create Shortcut", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
After you have this code, you can add the Custom Action to the installer to the Install Custom Actions area.
The notification code would be similar for the install process but needs to be added to the registry.

How can I get the CommonOpenFileDialog's InitialDirectory to be the user's MyDocuments path, instead of Libraries\Documents?

I'm using the CommonOpenFileDialog in the Windows API Code Pack as a folder picker dialog. I'm setting the InitialDirectory property to Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments). However, when I display the dialog, the path in the address bar is Libraries\Documents (not C:\users\craig\my documents as I'd expect). Additionally, if I just press the Select Folder button, I get a dialog saying that 'You've selected a library. Please choose a folder instead.'
Does someone know why my file path is being ignored, in favor of 'libraries\documents'? More importantly, how can I get the dialog to respect the InitialDirectory value I passed in?
The code I'm using for the dialog is:
if (CommonFileDialog.IsPlatformSupported)
{
var folderSelectorDialog = new CommonOpenFileDialog();
folderSelectorDialog.EnsureReadOnly = true;
folderSelectorDialog.IsFolderPicker = true;
folderSelectorDialog.AllowNonFileSystemItems = false;
folderSelectorDialog.Multiselect = false;
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
folderSelectorDialog.Title = "Project Location";
if (folderSelectorDialog.ShowDialog() == CommonFileDialogResult.Ok)
{
ShellContainer shellContainer = null;
try
{
// Try to get a valid selected item
shellContainer = folderSelectorDialog.FileAsShellObject as ShellContainer;
}
catch
{
MessageBox.Show("Could not create a ShellObject from the selected item");
}
FilePath = shellContainer != null ? shellContainer.ParsingName : string.Empty;
}
}
Thanks,
-Craig
First of all, I'm sorry it took me so long to understand your question.
The message I see is when I try this is:
Cannot operate on
'Libraries\Documents' because it is
not part of the file system.
There's not much more to say. A library is a virtual folder that is an amalgamation of various different real folders.
There's no real way to avoid this error. You have asked the dialog to return a folder and the user has not selected a folder. The dialog therefore cannot fulfil its part of the deal.
If you descend further into the folder structure, into real folders, then the dialog will return you a real value.
Instead of
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
try
folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

Simple silverlight open-file-dialog errors

A while back I wrote a silverlight user control which had a csv import/export feature. This has been working fine, until recently I discovered it erroring in one scenario. This may have been due to moving to Silverlight 3.
The Error:
Message: Unhandled Error in Silverlight 2 Application
Code: 4004
Category: ManagedRuntimeError
Message: System.Security.SecurityException: Dialogs must be user-initiated.
at System.Windows.Controls.OpenFileDialog.ShowDialog()
at MyControl.OpenImportFileDialog()
at ...
The Code:
private void BrowseFileButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(lblFileName.Text))
{
if (MessageBox.Show("Are you sure you want to change the Import file?", "Import", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
{
return;
}
}
EnableDisableImportButtons(false);
var fileName = OpenImportFileDialog();
lblFileName.Text = fileName ?? string.Empty;
EnableDisableImportButtons(true);
}
private string OpenImportFileDialog()
{
var dlg = new OpenFileDialog { Filter = "CSV Files (*.csv)|*.csv" };
if (dlg.ShowDialog() ?? false)
{
using (var reader = dlg.File.OpenText())
{
string fileName;
//process the file here and store fileName in variable
return fileName;
}
}
}
I can open an import file, but if i want to change the import file, and re-open the file dialog, it errors. Does anyone know why this is the case?
Also, I am having trouble debugging because placing a breakpoint on the same line (or prior) to the dlg.ShowDialog() call seems to cause this error to appear as well.
Any help would be appreciated?
You do two actions on one user click.
You show a messagebox which effectively uses your permission to show a dialog on user action.
You then try to show the dialog, since this is a second dialog on user action it's not allowed.
Get rid of the confirmation dialog and you'll be fine.
Remove Break Points before if (dlg.ShowDialog() ?? false) code will run its work for me.

Categories