Я работаю над школьным проектом, но я не могу понять эту последнюю ошибку. Предполагается открыть saveFileDialog, если первый оператор if возвращает false. Но вместо того, чтобы продолжать выполнение инструкции else, он сразу бросает исключение и никогда не открывает диалог saveFile. Это дает мне ошибку: Code: The path is not of a legal form.
C# Try/Catch Пропуски Вложенные If/Else Statement и Wont Open SaveDialog
Я не понимаю, в чем проблема. Пользователь должен иметь возможность выбрать путь в открывшемся диалоговом окне сохранения. Файл еще не существует, и он должен открыть диалог сохранения файла, чтобы сделать файл.
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!");
}
}
может быть 'currentFile' не существует. что такое сообщение об исключении? –
звучит как 'currentFile', содержит недопустимый путь. Какова его ценность? – juharr
Я просто запустил его с точками останова, а currentFile имеет значение «». Сообщение об исключении - «Сохранить отменено». Код: путь не имеет юридической формы. ' –