如何保存一个richtextbox数据到一个文本文件,而不使用对话框
本文关键字:一个 对话框 文件 richtextbox 何保存 保存 数据 文本 | 更新日期: 2023-09-27 18:02:32
我正在写一个程序来记录我的一天是如何度过的(非常类似于日记)。我已经设法让程序在这个阶段做我想做的一切,除了一件事。这将自动将richtextbox数据保存到带有创建日期和时间的.txt文件中。我可以得到它,保存文件,但它保存在文件夹TomJ记录我的生活文件。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);
}
}
看一下System中的File类。IO命名空间:
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");
您可以使用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);
}
}