Getting the last opened file in fileopen dialog box - c#

In FileOpen or FileSave dialogbox when I call them, they automatically go to the last opened path. This happens even if I close my application and open it. But how to get that path/file name to a textbox or variable?

it seems a bit weired but under Windows 7 it works with the folling:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
Try it and tell me if you need further help.

Presumably the information is stored somewhere in the depths of the registry (it's done by the unmanaged control to which OpenFileDialog is only a wrapper). The easiest would probably be to persist the path the last time the dialog was closed in your application somewhere where you can access it.

As mentioned here: What does the FileDialog.RestoreDirectory Property actually do?
They use the path from Environment.CurrentDirectory.

I am having a similar problem to Vicky, which goes as follows. I am developing in Visual Basic 2008 Express Edition under Vista Business SP2.
I have an application with an OpenFileDialog and a SaveFileDialog. When I call the OpenFileDialog on first running the application, it defaults to the directory from which the Application last opened/saved a file. However, this directory IS NOT "Environment.CurrentDirectory" which is set to "C:\Users\Brian\Documents\Visual Studio 2008\Projects\IFPM Analysis\IFPM Analysis\bin\Debug" and is not changed by either the OpenFileDialog or SaveFileDialog.
Later on in the Application, I call the SaveFileDialog, with the initial directory property (.InitialDirectory) set in the code to a default directory. When I subsequently call the OpenFileDialog, it defaults to the directory used by the SaveFileDialog. All the time, the value of "Environment.CurrentDirectory" is unchanged.
So, my question is, where is the directory that is being used by the OpenFileDialog and SaveFileDialog being stored? I assume it is something to do with the underlying FileDialog class, and I know persists even after the Application has been closed and restarted.
Ideally I want to be able to store the directory selected by the user from the OpenFileDialog and reset it after I have used the SaveFileDialog. While I can use the InitialDirectory property of the OpenFileDialog within the Application, this doesn't help me when I close the Application and restart it. Sadly, the typical user actions are:
start Application
open file with OpenFileDialog
save file with SaveFileDialog
leave Application
This means that when the user comes back to the Application, the default directory is the "wrong" one. I know that I can save the last used directory from the OpenFileDialog in my own configuration file so that it will persist outside of the Application, but that seems a little silly when Windows provides me with the same functionality, if only I knew where to look!
Any help gratefully received!
Thanks,
Brian.

The recent opened files list is stored in 2 places:
Recent Folder: The recent folder is usually located under C:\Documents and Settings[Your Profile]\Recent (The path is different under Windows Vista), and it contains shortcuts to the recently opened files.
Registry: Each time that a file is selected in save/open dialog-box, the filename is added to the files list under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSaveMRU
This method can help you to get the list:
public static string GetLastOpenSaveFile(string extention)
{
RegistryKey regKey = Registry.CurrentUser;
string lastUsedFolder = string.Empty;
regKey = regKey.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU");
if (string.IsNullOrEmpty(extention))
extention = "html";
RegistryKey myKey = regKey.OpenSubKey(extention);
if (myKey == null && regKey.GetSubKeyNames().Length > 0)
myKey = regKey.OpenSubKey(regKey.GetSubKeyNames()[regKey.GetSubKeyNames().Length - 2]);
if (myKey != null)
{
string[] names = myKey.GetValueNames();
if (names != null && names.Length > 0)
{
lastUsedFolder = (string)myKey.GetValue(names[names.Length - 2]);
}
}
return lastUsedFolder;
}
Success!
Iordan

Related

C# OpenFileDialog multiple filename filters including exclude

I have a requirement to allow users to open a specific file for processing. The open file dialog is currently
OpenFileDialog ofg = new OpenFileDialog
{
FileName = "BaseFileName*",
Filter = "CSV File (*.CSV)|*.csv",
Multiselect = false,
InitialDirectory = #"N:\Downloads"
};
However the process adds a suffix of _Processed along with timestamp data to the filename and I want to exclude these renamed files the next time the OpenFileDialog is used to prevent the user trying to reprocess the same file.
I have to leave the original files where they are for internal audit reasons.
So I need an additional filename filter of not equal to "_Processed".
Is there any way to do this with OpenFileDialog or does anyone know of a custom c#/.net component that can do this?
You are asking to omit specific items from the file dialog view.
According to MSDN, this is no longer possible as of Windows 7, but was possible previously.
The C# file dialogs (both WPF and WinForms) use the IFileDialog API.
Here is the function that could have made this work, but is no longer supported:
https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfilter
As it is, you are stuck with checking the file for correctness after the user has already selected it and confirmed it with OK.
You can help the situation a little bit: If you enjoy pain, then you can copy the whole IFileDialog COM interop code from the .NET source code, and implement IFileDialogEvents. This way, when the user clicks "OK", you can deny the selection and display an error before the dialog closes, leaving the dialog open so the user can select a different file.
If you are sane and you don't want to do that, then you'll have to open the dialog again after the verification fails.
The easy way is just saving the processed data with another extension e.g. "BaseFileName_Processed_20105640640.cvs1", that way you keep the data and your file dialog will not show this file.
Another way could be to call the OpenFileDialog() in an if statement (and compare the return to DialogResult.OK), then split the file name for {'_','.'}, then run a loop to count the occurrences of the word Processed( >0), and possibly as a safety check determine whether a timestamp is present in one of the split strings. Finally, reload the FileOpenDialog in the same folder when the wrong file was selected.

OpenFileDialog - How to prevent the default directory from being overwritten?

I'm trying to find a way to reset the initial/default directory after closing an OpenFileDialog. Consider the following example:
using (OpenFileDialog openFile = new OpenFileDialog())
{
// Example: This opens in the 'Desktop' directory
// User navigates to 'Documents' directory in the Form before selecting a file
DialogResult result = openFile.ShowDialog();
if (result == DialogResult.OK) MessageBox.Show(openFile.FileName);
}
// Somewhere else, this code then runs
using (OpenFileDialog openFile = new OpenFileDialog())
{
// Problem: This now opens in 'Documents' directory. Not good!
// How to open using the same default directory (ie: Desktop)?
DialogResult result = openFile.ShowDialog();
if (result == DialogResult.OK) MessageBox.Show(openFile.FileName);
}
Just to be clear, 'Desktop' is just an example, I won't actually know the initial directory as it's stored in the registry (if I understand correctly).
I tried using the RestoreDirectory option. This did not seem to have any effect. From what I've read elsewhere it's supposed to reset the Environment.CurrentDirectory back to its original value, which sounds reasonable. However, I don't think OpenFileDialog even uses Environment.CurrentDirectory since the value is never changed, and never matches what OpenFileDialog opens with (unless I manually browse to it).
Is there anything I might be missing here? Does anyone know how to stop overwriting whichever directory variable OpenFileDialog uses as its default?
The default directory is stored in the following registry key on Windows 7.
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32
IIRC, this could be different on other OS's, so you might want to find out the exact directory depending on your OS version.
So what you could do is to grab that value when your application launches, and save it in the memory, and set that to OpenFileDialog.InitialDirectory every time before you open the dialog.

how to Save File using C# Windows Application

I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));

How can I code defensively against potential unorthodox hard drive letters?

I can set a SaveFileDialog's InitialDirectory property to where my app will usually be installed like so:
saveFileDialog1.InitialDirectory = #"C:\Program Files\Waltons\Mountains";
...but as "there is one in every crowd," some may use a drive letter other than C for their hard drive? How can I set the InitialDirectory to whichever drive letter the user has specified?
UPDATE
I tried Alexei's code (had to change "Concat" to "Combine" and remove a superfluous ")":
saveFileDialog1.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), #"Waltons\Mountains");
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
// TODO: Finish
}
...but it does not open C:\Program Files\Waltons\Mountains
UPDATE 2
Saeb's suggestion seems to work, as the save file dialog opens in C:\Waltons\Mountains\bin\Debug
...which I hope/reckon would correspond to C:\Waltons on the user's machine (or D:\Waltons or Z:\Waltons or whatever).
I would have to append the "\Maps" I guess for the user - check that it's not running in Visual Studio or something and append that in that event.
Location that is writable by normal user would be better default location for save dialog. I.e. "my documents" via Environment.GetFolderPath passing one of Environment.SpecialFolder values:
var pathToMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.Personal));
If you need location where your program installed by default like program files
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "MyFolder");
or if you need path relative to program check How can I get the application's path in a .NET console application?.
Note that locations above are not writable by normal users and even admin unless you turn off UAC or explicitly "run as administrator" or change default permissions on these folders (either of approaches to bypass default permission have its drawbacks and one should perform serious security review if allowing regular users to write in programs/system folders).
Don't use hardcoded driver letters. Find the path in runtime. e.g.:
saveFileDialog1.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
You can use the environment variable systemroot to get the drive. Try opening a cmd prompt and entering set to see a list of all the environment variables avaliable and then use System.Envrionment.GetEnvironmentVariable ("systemdrive") and combine that with the rest of your path.

How to restrict filename modification in OpenFileDialog in C#

I have a C# .NET 3.5 program that uses an OpenFileDialog to retrieve a file for importing. It has two filters (*Domain*.* and *.*) and the *Domain*.* is chosen as the FilterIndex. I'm seeing a case of a disappearing file from the filters when it is modified within the OpenFileDialog.
Here are the steps the user will take to reproduce the problem:
In the program, open the OpenFileDialog. Ensure that the filter is set to *Domain*.*.
Find a file in the directory that matches the filter and change the file name so that it no longer matches the filter. Note: the file will disappear.
Change the filter to show all files *.*. Note: the file is not listed even though you're supposedly showing *.*.
At this point, you can open the folder in Windows Explorer and see that the file with the changed name exists. However, in the OpenFileDialog, it is no longer visible regardless of the filter that is used. The only way to see that file again is to close the OpenFileDialog and then reopen it.
Here is my code that creates the OpenFileDialog.
using(OpenFileDialog domainFileDialog = new OpenFileDialog())
{
domainFileDialog.CheckFileExists = true;
domainFileDialog.CheckPathExists = true;
domainFileDialog.Filter = "Domain Files (*Domain*.*)|*Domain*.*|All files (*.*)|*.*";
domainFileDialog.FilterIndex = 1;
domainFileDialog.Multiselect = false;
domainFileDialog.RestoreDirectory = true;
domainFileDialog.ShowReadOnly = true;
domainFileDialog.SupportMultiDottedExtensions = true;
domainFileDialog.Title = "Choose the Domain File to Import...";
domainFileDialog.ValidateNames = true;
\\ Perform Import functionality...
}
It seems as though when you open the OpenFileDialog and modify an existing file that matches the more restrictive filter so that it no longer matches the filter, the file disappears from visibility even when all files *.* are displayed.
Since I have no idea why this is happening, (and I'm open for suggestions as to how to fix it) is there any way to restrict a user from creating or modifying any of the files in the OpenFileDialog in hopes of preventing this problem?
First, I'd suggest you consider whether it is worth caring that the user might do this. If the FOD does this, every windows application has this feature, but you don't hear users complaining about it. So is it really an issue that needs fixing?
It wouldn't surprise me if the problem's related to the filter being for more than just a file extension - it's rather unconventional to do this. Maybe try it with an extension only and see if this is the cause.
Have you tried pressing F5 to refresh its cached data? I don't know if this would work in a FOD as it does in an explorer window, but it might be interesting to give it a try.
Having said all that, it would be trivial to filter keypresses (F2) and mouse clicks (right button) )(with some forms you could derive off it, or you could drop in a MessageFilter) to make it impossible for a user to access any UI that allows them to rename a file in the FOD. It would piss me off, as a user, if you broke the FOD in this waym though - much more than a renamed file "disappearing" under rare circumstances, anyway.
http://msdn.microsoft.com/en-us/library/microsoft.win32.openfiledialog.aspx
The OpenFileDialog doesn't itself support any such functionality. I think your best bet at this point is writing your own open-file dialog window. You would gain a great deal of control that way and it wouldn't take too long.

Categories

Resources