0

I am trying to create a file named "test.txt" in a folder named "test" in the current directory and append some lines of text into it.

I am using this code segment in a program but getting an exception saying that the file is already in use by another process. Is there any problem in this segment?

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);
Arghya C
  • 9,805
  • 2
  • 47
  • 66
user5404530
  • 27
  • 1
  • 10

1 Answers1

0

This will do the work as per your question. Explanation inline.

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

The reason behind the error you are getting is, you are creating a FileStream with File.Create, but you are not disposing before re-using that! If you want to go the File.Create path, you need to change your code like this

using(FileStream fs = File.Create(Path.Combine(path, "test.txt")))
{
    fs.Write(...);
}
Arghya C
  • 9,805
  • 2
  • 47
  • 66