gpt4 book ai didi

C# Try/Catch 跳过嵌套的 If/Else 语句并且不会打开 SaveDialog

转载 作者:行者123 更新时间:2023-11-30 23:27:56 25 4
gpt4 key购买 nike

我正在做一个学校项目,但我无法找出最后一个错误。它应该在第一个 if 语句返回 false 时打开一个 saveFileDialog。但是它没有继续进入 else 语句,而是直接抛出异常并且从不打开 saveFile 对话框。它给我以下错误:Code: The path is not of a legal form.

我不明白这是什么问题。用户应该能够在弹出的保存对话框中选择路径。该文件尚不存在,它应该打开保存文件对话框来创建文件。

private void btnSave_Click(object sender, EventArgs e)
{
// Declare StreamWriter object
StreamWriter outputFile;

// Try to write file
try
{
// If current file is > 0
if (new FileInfo(currentFile).Length > 0)
{
// Create output file using current file
outputFile = File.CreateText(currentFile);

// Loop through current file and write lines to output file
for (int i = 0; i < lstBoxLog.Items.Count; i++)
{
outputFile.WriteLine(lstBoxLog.Items[i].ToString());
}

// Close text file
outputFile.Close();
}

// Else open save dialog for user to save file
else
{
// If save file dialog is equal to dialog result
if (saveFile.ShowDialog() == DialogResult.OK)
{
// Open output file object with create text
outputFile = File.CreateText(saveFile.FileName);

// Set currentFile to = savefile dialog
currentFile = saveFile.FileName;

// Loop through each line and write to file
for (int i = 0; i < lstBoxLog.Items.Count; i++)
{
outputFile.WriteLine(lstBoxLog.Items[i].ToString());
}

// Close text file
outputFile.Close();
}

// Else show error message
else
{
// Display message box dialog
MessageBox.Show("Cannot save file.", "Not Saved");
}
}
}

// Display error message.
catch (Exception ex)
{
// Display message box dialog
MessageBox.Show("Save canceled. \n\nCode: " + ex.Message, "Save Error!");
}
}

最佳答案

try
{
if (File.Exists(currentFile))
{
if (new FileInfo(currentFile).Length > 0)
{
...
}
}
else
{
//show save file dialog
}

}
catch
{
...
}

关于C# Try/Catch 跳过嵌套的 If/Else 语句并且不会打开 SaveDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243419/

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