The process cannot access the file 'C:\csharp\notebook.txt' because it is being used by another process.
How is it used by another process, if I haven't used StreamWriter yet? I want to add new text to te file by using ReadLine().
using System;
using System.IO;
namespace NLP
{
class Exercise
{
static void Main(string[] args)
{
Directory.CreateDirectory(@"C:\csharp"); // creating the directory
File.Create(@"C:\csharp\notebook.txt"); // creating the file
if (File.Exists("C:\\csharp\\notebook.txt")) // checking if the file was succesfully created
Console.WriteLine("Success");
else
Console.WriteLine("bruh");
StreamWriter text = new StreamWriter(@"C:\csharp\notebook.txt");
}
}
}
I've checked if there are any processes using the file, but there are none.
It is because File.Create
returns a Stream
that you do not close.
You can simplify your code by writing:
File.AppendAllLines(@"C:\csharp\notebook.txt", new[] { "My new line" });
It will create the file if it does not exist