Validating InitialDirectory for SaveFileDialog? - c#

I'm opening a SaveFileDialog with an initial directory based on a user-defined path. I want make sure this path is valid before passing it in and opening the dialog. Right now I've got this:
Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();
if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory))
{
dialog.InitialDirectory = initialDirectory;
}
bool? result = dialog.ShowDialog();
However, it seems \ is slipping by and causing a crash when I call ShowDialog. Are there other values that could cause crashes? What rules does the InitialDirectory property need to follow?

The quick and easy way to fix it would be to get the full path:
dialog.InitialDirectory = Path.GetFullPath(initialDirectory);
This will expand relative paths to the absolute ones that the SaveFileDialog expects. This will expand just about anything that resembles a path into a full, rooted path. This includes things like "/" (turns into the root of whatever drive the current folder is set to) and "" (turns into the current folder).

Related

How to Get the Target Folder

I was just at Open directory dialog, and they said "get this package, and do this and this to get a folder select window to show up". Well, that all works great, using the Windows API Code Pack-Shell package. However, now I want to get the actual folder that is selected. I didn't notice them mentioning this anywhere.
I tried to do string folderLocation = Convert.ToString(dialog); (dialog is the variable for opening the folder window), but that only gave me like the property of the variable. I also tried this: CommonFileDialogResult result = dialog.ShowDialog();
string folderLocation = Convert.ToString(result);
But that just gave me "Ok" - which I take it is the result of it, instead of the actual folder.
The result of ShowDialog just indicates wether the user clicked OK, cancel, or just closed the window.
CommonOpenFileDialog can be used for both files and folders, so it's a bit surprising when used as a folder picker, but the path is stored in FileName.
var dlg = new CommonOpenFileDialog();
dlg.IsFolderPicker = true;
if(dlg.ShowDialog() == CommonFileDialogResult.Ok) {
Console.WriteLine(dlg.FileName);
}
If I understood correctly, you want to get Folder for a selected file? If that's the case, you can take FileInfo for that file, and extract folfer from it. Like this:
System.IO.FileInfo fInfo = new System.IO.FileInfo(oFD1.FileName);
MessageBox.Show(fInfo.DirectoryName);
PS. oFD1 is OpenFileDialog

FolderBrowserDialog add Custom Root Name

FolderBrowserDialog fd = new FolderBrowserDialog();
fd.RootFolder = string.Format("D:\\Project\\folder1\\folder2\\ Results\\{0}", FolderName);
in FolderBrowserDialog the Rootfolder Expects a type of environment.specialfolder
but i want to add my folder as root folder.
i dont want to set the SelectedPath as my custom path.
is there any way to do so.
thanks in advance.
There is no way to change the RootFolder to a custom folder because this is used as a fallback, which I think is what's happening in your code. .Net knows that special folders exist, whereas your custom directory may not.
It looks like you need to remove the space in here ...folder2\\ Results\\... and/or check the FolderName variable as this is producing a directory string that doesn't exist, therefore your dialog is using the RootFolder instead.
Default the RootFolder to Desktop
Set your custom folder as the SelectedPath property
fd.SelectedPath = string.Format("D:\Project\folder1\folder2\ Results\{0}", FolderName);
Call Show method of dialog
fd.ShowDialog();
Note that order of these settings need to be preserved, else will lead to wrong result.
More detail in following answered question
Set folder browser dialog start location
I've dropped a folder browser on a form called "folderBrowserDialog1" and the below seems to work. The special folder option is simply an option to allow the browsing to start in a "Special" folder. E.g. Windows etc.. and it provides a neat mechanism to set it without typing the full path. If you need a custom path, then set the SelectedPath property.
folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
//The above is optional. You don't need to set it.
folderBrowserDialog1.SelectedPath = #"C:\"; //Your path here
folderBrowserDialog1.ShowDialog();
Hope that helps

C# - Microsoft.Win32.SaveFileDialog Filename Issue

I have a problem where if you set the filename in the dialog box to a sub directory within the initial directory you set it to and then clicking 'Save', the dialog window doesn't actually save the file but opens the sub directory which I could still interact with.
For example If I set the initial directory for the dialog to 'C:\MainDir' and that directory consists of SubDir1, SubDir2, then in the save file dialog I could see that I am in the initial directory with two sub directories. If I set the filename to SubDir1 (no extension) in the dialog, and then I hit 'Save', what happens is instead of saving the file as 'filename.extension' the dialog opens the directory specified by the file name.
Here's what I currently have:
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ext;
dlg.AddExtension = true;
dlg.FileName = filename;
dlg.Filter = filter;
dlg.FileOk += OnFileDialogOk;
dlg.InitialDirectory = dir;
bool? dlgRes = dlg.ShowDialog();
Is this something that can be easily fixed?
Quick Answer: No.
You cannot override the default save method of Windows OS.
What you can do is perhaps to verify whether the filename you wanted to use (in this instance, SubDir) exists already as a directory. If it does, then you would need to change that name, as that will only manifest the behavior you've already seen.
Side Note: Just imagine you have a very important folder which contains critical files, and Windows would let you save a file that is named with that directory. That is a disaster waiting to happen.
The only ways I can think of doing this are a bit extreme:
You could roll your own dialog
You could modify the functionality of the standard dialog
The answers found here: Customizing OpenFileDialog could help with that.
I guess I should also note that while it may seem helpful to accommodate this kind of input and automatically append the extension, it'll be counter-intuitive to many users who will expect the default behaviour.
In short, I'd probably think twice about this.

Does OpenFileDialog InitialDirectory not accept relative path?

dialog is an OpenFileDialog class object, and I am using ShowDialog() method.
When I use path containing relative path, like:
dialog.InitialDirectory = "..\\abcd";
dialog.InitialDirectory = Directory.GetCurrentDirectory() + "..\\abcd";
ShowDialog() crashes; what I only can do is giving a definite path, starting with a disk drive:
dialog.InitialDirectory = "C:\\ABC\\DEF\\abcd";
In this case I want the path to be 1 level up of my .exe's current directory, and then downward to directory abcd.
The .exe's current path can be found by Directory.GetCurrentDirectory(), which is perfectly fine, but I cant go on with "..")
The directory hierarchy is like:
ABC
DEF
abcd (where I want to go)
defg (where .exe is at)
So, is there any method to use "..\\" with InitialDirectory?
Or I must use definite path with it?
Thanks!
I found my own answer!!
string CombinedPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "..\\abcd");
dialog.InitialDirectory = System.IO.Path.GetFullPath(CombinedPath);
See if the following gets you the path you're looking for:
dialog.InitialDirectory
= Path.Combine(Path.GetDirectoryName(Directory.GetCurrentDirectory()), "abcd");
The call to Path.GetDirectoryName strips off the last portion of the path, after the last directory separator, whether it's a file name or folder name.
Another way would be
openFileDialog.InitialDirectory = Path.Combine(Application.StartupPath,#"..\YourSubDirectoryName");

Is it possible to make a FolderBrowserDialog's default path show up in a library instead of the actual disk?

I know that if I set SelectedPath before I show the dialog I can get it to have a folder open by default when the dialog opens. However, the folder I want to use is very far down the list alphabetically. I have that same folder as one of my Libraries in Windows and it shows up at the of the listing, is there any way to have it default to the library version of the folder instead of the hard drive version of the folder?
Another potential solution would be if it did still use the drive version but it automatically scrolled the window down to where it was selected. Is there any way to do either of these solutions?
How it currently shows up
How I would like it to show up
Set your root folder and selected path as such and it will auto-scroll there for you on the dialog opening:
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.RootFolder = Environment.SpecialFolder.MyComputer;
dlg.SelectedPath = #"E:\Vetcentric";
dlg.ShowDialog();
The problem you run into is that if you watch the property assignments after selecting a folder located in the libraries hierarchy, it will still assign it to the genereic path that you would get via going through my computer.
Use a Reset() call. This will make it auto-scroll.
string prevpath = folderBrowserDialog1.SelectedPath;
folderBrowserDialog1.Reset();
folderBrowserDialog1.SelectedPath = bc.myWorkingDir;
folderBrowserDialog1.ShowNewFolderButton = true;
DialogResult dr = folderBrowserDialog1.ShowDialog();
if (dr == DialogResult.OK || dr == DialogResult.Yes)
{
bc.myWorkingDir = folderBrowserDialog1.SelectedPath;
}
folderBrowserDialog1.SelectedPath = prevpath;
Just set the path Libraries\VetCentric...
before you open should do it I think.
The easiest way would probably be to put shortcuts to the folders you want into your starting folder. Then, just double click on the shortcut and it will take you to your folder.
Otherwise you will need to use the Shell Library API
See: Using Libraries in your Program

Categories