How to disable checked file in WPF OpenFileDialog?

My WPF application uses Microsoft.Win32.OpenFileDialog to select the SQL Server 2008 database to open.

It works fine, but for one problem: when the database selected in the dialog box has been open for some time since the last boot, the file seems to be open on the SQL server in the background (even if it does not open my application and my application has been restarted). This leads to the warning "the file is being used by another application" when you click OK in OpenFileDialog, and I cannot use the dialog box to open this particular database until the computer restarts. It seems that OpenFileDialog is trying to open the selected file and does this by detecting that it is already open by another application (SQL Server). How to disable OpenFileDialog from trying to open the selected file and just return the file name of the selected file without any checks?

My code is as follows:

public void OpenDatabase() { // Let user select database to open from file browser dialog // Configure open file dialog box var dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = ""; // Default file name dlg.DefaultExt = ".mdf"; // Default file extension dlg.Filter = "Databases (.mdf)|*.mdf|All Files|*.*"; // Filter files by extension dlg.CheckFileExists = false; dlg.CheckPathExists = false; // Show open file dialog box bool? result = dlg.ShowDialog(); // Gives file in use warning second time! // Process open file dialog box results if (result == true) { // Open document string filename = dlg.FileName; TryOpenDatabase(filename); } } 
+4
source share
2 answers

The main option is OFN_NOVALIDATE for earlier versions of Windows, FOS_NOVALIDATE for the Vista dialog, which you get on later versions of Windows and .NET. Description from MSDN:

Do not check situations that would prevent the application from opening the selected file, for example, access violations or denied access.

This is what you see now, a dialog box displays a violation of access to the database file. This parameter is actually displayed in the OpenFileDialog shell class, add this line of code to fix your problem:

  dlg.ValidateNames = false; 
+5
source

The MSDN Online has this message

In the OpenFileDialog API, you can disable it using

 ValidateNames = false 

on Dialog .

+3
source

All Articles