wpf - 如何在 WPF OpenFileDialog 中禁用正在使用的文件检查?

标签 wpf openfiledialog

我的 WPF 应用程序使用 Microsoft.Win32.OpenFileDialog 来选择要打开的 SQL Server 2008 数据库。

它工作正常,但有一个问题:当对话框中选择的数据库在上次启动后的某个时间之前被打开时,该文件似乎在后台被 SQL 服务器保持打开状态(即使它没有被我的应用程序和我的应用程序打开)应用程序已重新启动)。当在 OpenFileDialog 中单击 OK 时,这会导致“文件被另一个应用程序使用”警告,并且在重新启动计算机之前我无法使用该对话框打开该特定数据库。似乎 OpenFileDialog 尝试打开选定的文件,这样做会发现它已被另一个应用程序(SQL Server)打开。如何禁用 OpenFileDialog 尝试打开所选文件并仅返回所选文件的文件名而不进行任何检查?

我的代码如下所示:

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);
    }
}

最佳答案

对于早期的 Windows 版本,底层选项是 OFN_NOVALIDATE,对于您在更高版本的 Windows 和 .NET 上获得的 Vista 对话框,则是 FOS_NOVALIDATE。来自 MSDN 的描述:

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



这就是您现在看到的情况,对话框看到数据库文件上的共享冲突。这个选项实际上暴露在 OpenFileDialog 包装类上,添加这行代码来解决你的问题:
  dlg.ValidateNames = false;

关于wpf - 如何在 WPF OpenFileDialog 中禁用正在使用的文件检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14109827/

相关文章:

.net - Silverlight 浏览器应用程序到桌面应用程序

c# - Interop 字进程不会立即关闭

wpf - WPF à la Clean Code 中的命令行参数和 "global settings"

wpf - 在任何一个单元格中出现一些验证错误后如何编辑数据网格中的行

.net - 带有大字体的 Windows 对话框

c# - 打开文件对话框中的strFileName

wpf - 使用迁移到 LocalDB 的 CodeFirst,我可以指定*在哪里*创建数据库吗?

c++ - WT 保存文件对话框窗口?

c# - 类似于 MS Paint 的 SaveFileDialog 的 OpenFileDialog 扩展

c# - 防止用户浏览 OpenFileDialog 中的其他地方