Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading