我试图在当前目录中名为"test"的文件夹中创建一个名为"test.txt"的文件,并将一些文本行添加到其中。
我在一个程序中使用这个代码段,但得到一个异常,说file is already in use by another process
。这部分有什么问题吗?
DateTime now = DateTime.Now;
string time = now.ToString();
string id="test";
string path2 = Path.Combine(Environment.CurrentDirectory, id);
string path=Directory.GetCurrentDirectory();
string FileName = Path.Combine(path2, id + ".txt");
File.Create(FileName);
string fullPathName2 = Path.GetFullPath(FileName);
File.AppendAllText(fullPathName2, time + Environment.NewLine);
这将按照您的问题完成工作。解释内联。
string time = DateTime.Now.ToString();
string path = Path.Combine(Environment.CurrentDirectory, "test"); //test folder in current directory
if (!Directory.Exists(path)) //create test directory, if directory does not exist
Directory.CreateDirectory(path);
string fileName = Path.Combine(path, "test.txt"); //the file name
File.AppendAllText(fileName, time + Environment.NewLine); //write data to file
你得到的错误背后的原因是,你正在用File.Create
创建一个FileStream
,但你没有在重用之前处理它!如果你想打开文件。创建路径,您需要像这样更改代码
using(FileStream fs = File.Create(Path.Combine(path, "test.txt")))
{
fs.Write(...);
}