写入文件,目录错误

时间:2017-07-19 19:36:45

标签: c#

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

1 个答案:

答案 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});
  }