Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable file in use check in WPF OpenFileDialog?

My WPF app is using the Microsoft.Win32.OpenFileDialog to select a SQL Server 2008 database to open.

It works OK but for one issue: When the database selected in the dialog was previously opened at some time since last boot, the file seems to be held open by SQL server in the background (even when it is not opened by my app and my app has been restarted). This causes a "file is used by another application" warning when OK is clicked in the OpenFileDialog and i can not use the dialog to open that particular database until the computer is rebooted. It seems the OpenFileDialog tries to open the file selected and doing that discovers that it is already opened by another app (SQL Server). How do i disable the OpenFileDialog from trying to open the selected file and just return the filename of the selected file without any checks?

My code looks like this:

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);
    }
}
like image 352
Liell Avatar asked Feb 19 '23 00:02

Liell


2 Answers

The underlying option is OFN_NOVALIDATE for early Windows versions, FOS_NOVALIDATE for the Vista dialog you get on later versions of Windows and .NET. The description from MSDN:

Do not check for situations that would prevent an application from opening the selected file, such as sharing violations or access denied errors.

Which is what you see happening now, the dialog sees a sharing violation on the database file. This option is in fact exposed on the OpenFileDialog wrapper class, add this line of code to fix your problem:

  dlg.ValidateNames = false;
like image 124
Hans Passant Avatar answered Feb 20 '23 14:02

Hans Passant


The MSDN forum has a post about this

It is in the OpenFileDialog API, you can turn that off using

ValidateNames = false

on the Dialog.

like image 29
TomTom Avatar answered Feb 20 '23 13:02

TomTom