我正在开展一个学校项目,但我无法弄清楚这最后一个错误。当第一个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!");
}
}
答案 0 :(得分:2)
try
{
if (File.Exists(currentFile))
{
if (new FileInfo(currentFile).Length > 0)
{
...
}
}
else
{
//show save file dialog
}
}
catch
{
...
}
答案 1 :(得分:0)
根据罗布的建议,这就是我所使用的。
try
{
// If current file is > 0
if (currentFile.Length > 0)
{
// Create output file using current file
outputFile = File.CreateText(currentFile);