我将以下代码添加到保存按钮:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
writer.Write(twexit.Text); // twexit is previously created
writer.Close();
fs.Close();
}
当我键入文件名并单击“保存”时,表示该文件不存在。我知道它不存在,但我设置了FileMode.Create
。那么,如果它不存在,它不应该创建文件吗?
答案 0 :(得分:4)
SaveFileDialog
中有一个选项CheckFileExists
,如果所选文件不存在,将导致对话框显示该消息。您应该将此设置保留为false(这是默认值)。
答案 1 :(得分:1)
你可以简单地使用它:
File.WriteAllText(saveFileDialog1.FileName, twexit.Text);
而不是很多代码与流。它会创建新文件或覆盖它。 文件是System.Io的类。如果您想说文件是否存在,请使用
File.Exist(filePath)
再见
答案 2 :(得分:0)
像这样使用:
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "csv files (*.csv)|*.csv";
dlg.Title = "Export in CSV format";
//decide whether we need to check file exists
//dlg.CheckFileExists = true;
//this is the default behaviour
dlg.CheckPathExists = true;
//If InitialDirectory is not specified, the default path is My Documents
//dlg.InitialDirectory = Application.StartupPath;
dlg.ShowDialog();
// If the file name is not an empty string open it for saving.
if (dlg.FileName != "")
//alternative if you prefer this
//if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK
//&& dlg.FileName.Length > 0)
{
StreamWriter streamWriter = new StreamWriter(dlg.FileName);
streamWriter.Write("My CSV file\r\n");
streamWriter.Write(DateTime.Now.ToString());
//Note streamWriter.NewLine is same as "\r\n"
streamWriter.Write(streamWriter.NewLine);
streamWriter.Write("\r\n");
streamWriter.Write("Column1, Column2\r\n");
//…
streamWriter.Close();
}
//if no longer needed
//dlg.Dispose();