0

我正在编写一个程序,它将记录我的一天过得怎么样(非常类似于日记)。我已经设法让程序在这个阶段做我想做的一切,除了一件事。这是为了自动将富文本框数据保存到带有创建日期和时间的 .txt 文件中。我可以让它保存文件,但如果尚未创建文件夹“记录我的生活文件”,它会将其保存在 TomJ 文件夹中,作为记录我的生活 files.txt,我想要将它保存在文件夹中将我的生活文件记录为(日期 + 时间).txt。

总结一下我的问题:如何编辑我的代码以自动将 reviewtxtbox 保存在文件夹记录我的生活文件中,名称为日期+时间?

我是一个新手,我只花了大约 6 个小时使用 C#,但我之前做过一些其他的编程工作,所以如果你能简单地解释你的答案,我会很高兴。:) 谢谢我需要编辑的代码如下:

//creat directory for folders
if (!Directory.Exists(@"C:\Users\TomJ\Record My Life files")) 
{
}
else
{
    Directory.CreateDirectory(@"C:\Users\TomJ\Record My Life files");
    MessageBox.Show("Directory Created for Diary Entries");
}

private void savebutton_Click_1(object sender, EventArgs e)
{
    try
    {
        string date = datepckr.Text;
        string time = timetxtbox.Text;
        savefile.FileName = date + time;
        savefile.DefaultExt = "*.txt*";
        savefile.Filter = "TEXT Files|*.txt";
        reviewtxtbox.SaveFile(@"C:\Users\TomJ\Record My Life files\", RichTextBoxStreamType.PlainText);
        MessageBox.Show("Your day has been saved!");
    }
    catch(Exception etc)
    {
        MessageBox.Show("An error Ocurred: " + etc.Message);
    }
}
4

2 回答 2

1

看一下 System.IO 命名空间中的 File 类:

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

特别是,您可能会发现 File.AppendAllText 或 File.CreateText 很有用。

两者都将完整的文件路径和文件内容作为参数,并假设您的程序对您的文件夹具有写权限,该文件将根据您使用的函数调用附加到、创建或替换。

一个例子是:

string folder = @"C:\Users\TomJ\Record My Life files\" 
string fileName = "testFile.txt";  

File.AppendAllText(folder + fileName, "test text to write to the file");
于 2013-03-06T21:13:10.460 回答
0

您可以使用File.WriteAllText(path, contents). 像这样的东西应该工作:

//creat directory for folders
if (!Directory.Exists(@"C:\Users\TomJ\Record My Life files")) 
{
}
else
{
   Directory.CreateDirectory(@"C:\Users\TomJ\Record My Life files");
   MessageBox.Show("Directory Created for Diary Entries");
}

private void savebutton_Click_1(object sender, EventArgs e)
{
  try
  {
    string content = new TextRange(reviewtxtbox.Document.ContentStart, reviewtxtbox.Document.ContentEnd).Text;
    string date = datepckr.Text;
    string time = timetxtbox.Text;
    string path = @"C:\Users\TomJ\Record My Life files\" + date + time + ".txt";
    File.WriteAllLines(path,content);
    MessageBox.Show("Your day has been saved!");
  }
  catch(Exception etc)
  {
    MessageBox.Show("An error Ocurred: " + etc.Message);
  }
}
于 2013-03-06T21:10:53.940 回答