gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:35:07 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com