C# - Microsoft.Win32.SaveFileDialog Filename Issue - c#

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.

Related

Detect when OpenFileDialog returns a downloaded URL/URI

I'm using OpenFileDialog (.Net Framework 4, Windows 10) and I've noticed that it will allow the user to specify a URL as the file name (e.g., http://somewebsite/picture.jpg). This is very useful for my application, so I don't intend to disable it. The way it works is downloading the file into the user's temp directory and returning the temporary file name in the dialog's Filename property. This is nice, except for the fact that the user starts to build up garbage in his/her temp directory.
I would like to tell when a file was downloaded by the OpenFileDialog class (as opposed to a previously existing file), so I can clean up by deleting the file after use. I could check if the file's directory is the temp directory, but that's not very good since the user might have downloaded the file him/herself.
I've tried intercepting the FileOK event and inspect the Filename property to see if it is an HTTP/FTP URI, but despite what the documentation says ("Occurs when the user selects a file name by either clicking the Open button of the OpenFileDialog") it is fired after the file is downloaded, so I don't get access to the URL: the Filename property already has the temporary file name.
EDIT: This is an example of what I'like to do:
Dim dlgOpenFile As New System.Windows.Forms.OpenFileDialog
If dlgOpenFile.ShowDialog(Me) <> Windows.Forms.DialogResult.OK Then Return
''//do some stuff with dlgOpenFile.Filename
If dlgOpenFile.WasAWebResource Then
Dim finfo = New IO.FileInfo(dlgOpenFile.Filename)
finfo.Delete()
End If
In this example, I've imagined a property to dlgOpenFile "WasAWebResource" that would tell me if the file was downloaded or originally local. If it's the first case, I'll delete it.
There's no obvious way to do this, but as a workaround, how about checking where the file lives? It looks like by default this dialog downloads files to the users Temporary Internet Files directory, so you could introduce some code that looks something like this:
FileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string temporaryInternetFilesDir = Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
if (!string.IsNullOrEmpty(temporaryInternetFilesDir) &&
dialog.FileName.StartsWith(temporaryInternetFilesDir, StringComparison.InvariantCultureIgnoreCase))
{
// the file is in the Temporary Internet Files directory, very good chance it has been downloaded...
}
}

C# WPF - Only allow certain file extensions

I have an OpenFileDialog and I only want to allow .txt as a valid file for the users.
I know I can add a Filter to the OpenFileDialog like so:
var dialog = new OpenFileDialog();
dialog.DefaultExt = ".txt";
dialog.Filter = "Text Files (*.txt)|*.txt";
var result = dialog.ShowDialog();
// Do something with the result
The problem however, is that I can still directly say something like "test.jpg" in the OpenFileDialog and then it opens this uploads this .jpg file. (Obviously it goes wrong somewhere later, but that doesn't matter for now.) I just want to know how I can restrict the user to only add ".txt" files, nothing else? (By directly validation it inside the OpenFileDialog, instead of doing it somewhere later.)
You cant do that only in OpenFileDialog and even if you could its a bad limitation.
Using the *.txt example there are multiple files extensions that are plain text inside, *.bat or all the codding file extensions *.cs, *.js, etc...
You should not limit the user on what file he can put on it.
For more complex file types if your program cant handle the file passed by the user you should show an error not prevent the user from passing the file.

Where are paths previously used in the program stored (e.g. FileDialog paths)?

According to this msdn article one of the sources for InitialDirectory property used in FileDialog is:
A path that was previously used in the program, perhaps retained from the last directory or file operation.
...
So if you selected your first file from folder x, the next time you try to select a file it will open up the FileDialog with with folder x selected (saving you having to navigate there).
Playing around with notepad this seems to carry across opening a file, saving a file, opening a file and even when printing with "Microsoft XPS Document Writer" which brings up it's own dialog.
So my question is where is this value stored between dialogs? I would like to be able to see what it is and potentially change it? The specific area i would like to change it is in the "Microsoft XPS Document Writer" printer which brings up it's own dialog. So it's not as simple as just setting the initalDirectory Value.
It's stored in the registry, somewhere in HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\ (LastVisitedPidlMRU).
You should take a look at this link:
MRU locations are what you are looking at!
Here's a way for accessing it:
var openFileDialog1 = new OpenFileDialog();
string path = openFileDialog1.InitialDirectory;
// you can change path if you want
openFileDialog1.InitialDirectory = path;
// after you are donw you can display you dialog
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// do something
}
Another way is to use Directory.SetCurrentDirectory method which sets the application's current working directory
And from Microsoft website, it is stored at this location in the registry:
//The MRU lists for Windows Explorer-style dialog boxes are stored by file type for each user in the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSaveMRU
hope this helps

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

Validating InitialDirectory for SaveFileDialog?

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).

Categories