我的系统上创建程序的第一个按钮点击一个文本文件,并追加各种各样的事情压在其它按钮的点击。理想情况下,所有内容都将保存在最后,但由于它是一个使用定时器的监控系统,因此某些数据需要在特定时间写入文件或丢失。C# - 程序不会覆盖现有的文本文件
通过点击第一个按钮(btnStart),程序找到/创建主文件夹(使用常量字符串给定名称)并找到/创建子文件夹(使用在文本框之前输入的文本点击按钮),这将文本文件的目录,如字符串(文件名如下图所示):
private void createDirectory()
{ //create output file in this folder using owner name and current date
//main folder path (contains all files output from system)
string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Horse Monitoring Records";
//sub folder path (each patient has individual subfolder)
string subDirectory = rootDirectory + "\\" + txtPatName.Text + "/" + txtOwnerName.Text;
//file name (patient has file created for each operation)
fileName = subDirectory + "\\" + txtOwnerName.Text + "/(" + DateTime.Now.Date.ToString("dd-MM-yyyy") + ").txt";
if (!Directory.Exists(rootDirectory)) //if main folder does not exist...
{
Directory.CreateDirectory(rootDirectory); //create it in My Documents
}
if (!Directory.Exists(subDirectory)) //if patient sub folder does not exist...
{
Directory.CreateDirectory(subDirectory); //create it in Patient-Owner format
}
}
的称为下一个功能文本的第一位写入文件,如下图所示:
private void saveFileDetails()
{
//Once case details have been entered, create new file using these details and add data input structure
StreamWriter consoleFile = new StreamWriter(fileName, true);
consoleFile.WriteLine("------------------------------------------- Case Details -------------------------------------------");
consoleFile.WriteLine("\n\n");
//patient and vet details
...
}
最初,当我设置这个功能,我没有在在函数的第一行包含StreamWriter的'true'重载。这导致运行时错误,告诉我文本文件无法打开,因为它已被另一个进程打开。
由于我添加了'true'重载,系统工作正常,但是我刚刚遇到了一个问题,一旦文本文件被创建,它就不能被覆盖,因为StreamWriter通常会使用文本文件相同的路径。
我需要能够为他们成为了一段时间后,已废弃,并确实需要更换,以覆盖文件,没有任何人有任何想法,我可以从这里去解决这个问题?
谢谢, 马克