SaveFileDialog 阻止可移动驱动器 [英] SaveFileDialog blocking removeable drive

查看:32
本文介绍了SaveFileDialog 阻止可移动驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 SaveFileDialog 让用户选择可移动驱动器上的目录和文件名.之后我创建了那个文件,写入它,然后再次关闭它.

I'm using a SaveFileDialog to let a user pick a directory and filename on a removeable drive. Afterwards I create that file, write to it, and close it again.

到那时文件本身没有被锁定(可编辑、可删除),但我无法弹出驱动器,因为 Windows 声称它仍在使用中.我必须在弹出之前退出应用程序.

By then the file itself is not locked (editable, deleteable), but I can't eject the drive because windows claims it is still in use. I have to exit the application before an eject is possible.

顺便说一句,即使我只使用 SaveFileDialog 选择文件,驱动器也会被锁定.在对话框上点击取消"不会导致问题

Incidentally the drive gets locked even when I only pick the file with the SaveFileDialog. Hitting "Cancel" on the dialog doesn't cause the problem

SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ".csv";
dlg.InitialDirectory = mySettings.defaultPath;
dlg.Filter = "(CSV-Dateien) *.csv|";
dlg.FileName = exportDate.ToString("yyyy-MM-dd") + ".csv";

if (dlg.ShowDialog() != DialogResult.OK){
    // USB-Drive is ejectable
}else{
    // USB-Drive is locked
}

推荐答案

I found 2 Solutions:

I found 2 Solutions:

一旦用户单击保存",对话框就会更改当前工作目录.阻止可移动驱动器的不是文件,而是程序本身.

The Dialog changes the current working directory once the user clicks "save". It's not the file that was blocking the removable drive, but the program itself .

所以你要么需要在完成后重新调整工作目录:

So you either need to readjust the working directory once you're done:

String oldDir = Directory.GetCurrentDirectory();
// ... do dialog...
Environment.CurrentDirectory = oldDir;

或者你只是在调用 ShowDialog() 之前配置文件对话框来恢复目录

or you simply configure the file dialog to restore the directory before calling ShowDialog()

dlg.RestoreDirectory = true;
dlg.ShowDialog()

这篇关于SaveFileDialog 阻止可移动驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆