C# Try/Catch 嵌套步骤 If/Else 语句且不会打开保存对话框

C# Try/Catch Skips Nested If/Else Statement and Wont Open SaveDialog

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

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

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
{
  ...
}

根据 Rob 的建议,这就是我使用的。

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