【发布时间】:2016-08-12 02:04:00
【问题描述】:
尝试编写一些代码来检索文件的文件路径,以便稍后在 ReadFile() 函数中使用它,但遇到了一些问题。
我的目标是实现一个 MessageBox,它输出带有重试和关闭按钮的错误消息,两者都可以正常工作。
当执行以下代码时,它只是循环 try 块并且永远不会进入 catch 块,这就是我希望它在不选择文件或单击 OpenFileDialog 上的取消时执行的操作。
下面是我目前正在使用的代码..
public static string GetFile() {
MyLog.Write(@"Begin OpenFileDialog Process", LogFormat.Evaluate);
var path = _lastFilePath != string.Empty ? _lastFilePath : GetBaseDirectory();
if (path == null || !Directory.Exists(path))
path = Assembly.GetExecutingAssembly().CodeBase;
var dialog = new OpenFileDialog {
InitialDirectory = path,
Filter = @"Text|*.txt|All|*.*",
RestoreDirectory = true
};
var result = DialogResult.Retry;
while (result == DialogResult.Retry) {
try {
if (dialog.ShowDialog() != DialogResult.OK) {
MyLog.Write(@"File Retrieval was Unsuccessful", LogFormat.Result);
} else {
MyLog.Write($"FilePath: {dialog.FileName}", LogFormat.Process);
MyLog.Write(@"File Retrieval was Successful", LogFormat.Result);
_lastFilePath = Path.GetDirectoryName(dialog.FileName);
return dialog.FileName;
}
} catch when (result == DialogResult.Retry) {
MyLog.Write("No File Selected", LogFormat.Error);
result = MessageBox.Show(@"Please select a file..", @"No File Selected!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);
if (result == DialogResult.Abort) throw;
return null;
}
}
return null;
}
我已尝试将代码调整为 similar question,但我很难理解为什么该逻辑在我的上下文中不起作用。
我做错了什么?
编辑: 使用以法莲的回答,我能够想出以下似乎可行的方法..
// USED TO RETRIEVE THE FILENAME IN A OPENFILEDIALOG
public static string GetFile() {
MyLog.Write(@"Begin OpenFileDialog Process", LogFormat.Evaluate);
var path = _lastFilePath != string.Empty ? _lastFilePath : GetBaseDirectory();
if (path == null || !Directory.Exists(path))
path = Assembly.GetExecutingAssembly().CodeBase;
var dialog = new OpenFileDialog {
InitialDirectory = path,
Filter = @"Text|*.txt|All|*.*",
RestoreDirectory = true
};
var result = DialogResult.Retry;
while (result == DialogResult.Retry) {
if (dialog.ShowDialog() != DialogResult.OK) {
MyLog.Write(@"File Retrieval was Unsuccessful", LogFormat.Result);
MyLog.Write("No File Selected", LogFormat.Error);
result = MessageBox.Show(@"Please select a file..", @"No File Selected!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);
if (result == DialogResult.Abort || result == DialogResult.Cancel) { break; }
if (result == DialogResult.Retry) { return GetFile(); }
}
MyLog.Write($"FilePath: {dialog.FileName}", LogFormat.Process);
MyLog.Write(@"File Retrieval was Successful", LogFormat.Result);
_lastFilePath = Path.GetDirectoryName(dialog.FileName);
return dialog.FileName;
}
return null;
}
【问题讨论】:
-
你把它放在调试器里了吗?
-
catch语句永远不会触发,因为在try部分中不会引发异常。
标签: c# dialog openfiledialog