0

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.

Michał
  • 23
  • 4
  • 1
    Why don't you let `StreamWriter` create the file? as you can read in the documentation https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=net-7.0#system-io-streamwriter-ctor(system-string) `If the file exists, it is overwritten; otherwise, a new file is created.` – Rand Random Jun 07 '23 at 13:47
  • 2
    File.Create return a FileStream that holds a handle onto that file. You don't use the return but it there nevertheless. You might want to give the returned stream into the constructor of the StreamWriter instead of the things you do inbetween. And after usage dispose the StreamWriter. – Ralf Jun 07 '23 at 13:48
  • 1
    `File.Create` documentation | https://learn.microsoft.com/en-us/dotnet/api/system.io.file.create?view=net-7.0 | `The file is opened with read/write access and must be closed before it can be opened by another application.` – Rand Random Jun 07 '23 at 13:50

1 Answers1

1

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

Magnus
  • 45,362
  • 8
  • 80
  • 118
  • 1
    Want to point out - `AppendAllLines` is assuming an existing file should **not** be overwritten, if it should be overwriten use `File.WriteAllLines` instead – Rand Random Jun 07 '23 at 13:56