"The process cannot access the file — because it is being used by another process" when making txt file C#

string path = @$"c:\Users\asmet\Desktop\Database1/{username}";

if (File.Exists(path) == false)
{
    Console.WriteLine("Creating new file..");
    File.Create(path);
          
    // this is where the error is
    using (StreamWriter sw = new StreamWriter(path, true)) 
    {
        sw.WriteLine(DateTime.Now);
        sw.WriteLine($"rf = {rf}");
        sw.WriteLine($"pf = {pf}");
        sw.WriteLine($"sf = {sf}");
        sw.Close();
    }
}

I’m super new to C# and I don’t really know what I am doing, but whenever I try to make a new file to safe rf, pf, and sf which are all number values it crashes.

This is in VS Code in a console application.

Username is from Console.ReadLine() in earlier code

Exact error message :

System.IO.IOException: ‘The process cannot access the file ‘c:\Users\asmet\Desktop\Database1\ausernameientered’ because it is being used by another process.’

DataBase1 is just a folder

I’ve tried looking at forms relating to the issue but after awhile of searching I never found a solution, I want the code to make a new file at the location specified and then put the values in the text document, then close it, so I can save and look at the data later for a school project.

What happened is it crashes every time after I enter in the "username" and it tries to create a new file.

>Solution :

If you take out:

        File.Create(path);

it might work.

StreamWriter(String, Boolean)
Initializes a new instance of the
StreamWriter class for the specified file by using the default
encoding and buffer size. If the file exists, it can be either
overwritten or appended to. If the file does not exist, this
constructor creates a new file
.

Leave a Reply