public partial class Form1 : Form
{
string path = $@"C:\Journal";
string fileName = @"";
string compact = "";
public Form1()
{
InitializeComponent();
fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt";
compact = (path + @"\" + fileName);
}
private void btnWrite_Click(object sender, EventArgs e)
{
if(File.Exists(fileName))
{
StreamWriter myWriter = new StreamWriter(compact, true);
myWriter.WriteLine(txtDisplay.Text);
myWriter.Close();
}
else
{
StreamWriter myWriter = new StreamWriter(compact, true);
myWriter.WriteLine(txtDisplay.Text);
myWriter.Close();
}
}
我正在尝试使用每月日历日期作为文件名将多行文本框中的内容写入文件。我不断收到目录不存在的错误。我不确定自从我在路径中创建文件夹以来的原因,我很感激帮助。
System.IO.DirectoryNotFoundException was unhandled
答案 0 :(得分:0)
看来,你必须创建目录。另一个问题是
fileName = monthCalendar1.SelectionRange.Start.ToShortDateString() + ".txt";
因为短日期时间格式可以包含文件名中禁止的'/'
或'\'
。
public Form1() {
InitializeComponent();
// ToString(...) we don't want / or \ in the file's name
fileName = monthCalendar1.SelectionRange.Start.ToString("dd'.'MM'.'yyyy") + ".txt";
compact = Path.Combine(path, fileName);
}
private void btnWrite_Click(object sender, EventArgs e) {
Directory.CreateDirectory(Path.GetDirectoryName(compact));
// Or File.AppendAllText(compact, txtDisplay.Text);
File.AppendAllLines(compact, new string[] {txtDisplay.Text});
}