BlackVikingPro
BlackVikingPro

Reputation: 95

File being used by another process

I have this problem in C# that this code gets executed, and it does not go through, it gives me an error "File being used by another process" (or similar). I've tried looking for answers on Stack, but I couldn't quite put together all of it. I attempted to insert some more code (like they said) there, but just hands me more errors. Please help, many thanks in advance!

Below is my current code =>

// let's create example.py
string path = @"C:\example.py";
var stream = new FileStream(path, FileAccess.Read);
var reader = new StreamReader(stream);
if (!File.Exists(path)) {
    File.Create(path);
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# code to insert into target file");
} else if (File.Exists(path)) {
    System.IO.File.WriteAllText(@"C:\example.py", string.Empty); // clear contents
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# more code to insert into example.py");
}

This is my original code (no fix attempts) =>

// let's create example.py
string path = @"C:\example.py";
if (!File.Exists(path)) {
    File.Create(path);
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# code to insert into target file");
} else if (File.Exists(path)) {
    System.IO.File.WriteAllText(@"C:\example.py", string.Empty); // clear contents
    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("# more code to insert into example.py");
}

Upvotes: 2

Views: 1675

Answers (3)

BlackVikingPro
BlackVikingPro

Reputation: 95

I have found this works entirely ->

// let's create example.py
const string path = @"C:\example.py";
using (FileStream fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
using (TextWriter sw = new StreamWriter(fileStream))
{
    {
        sw.WriteLine("First line");
        sw.WriteLine("Second line");
        sw.Close();
    }
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

You have to close FileStream which is returned by File.Create:

  File.Create(path).Close();

see MDSN for details

https://msdn.microsoft.com/en-us/library/d62kzs03(v=vs.110).aspx

A better approach, however, is just to write into file:

  if (File.Exists(path))
    File.AppendAllText(path, "# more code to insert into example.py");
  else 
    File.AppendAllText(path, "# code to insert into target file");  

Or even

File.AppendAllText(path, File.Exists(path) 
  ? "# more code to insert into example.py"
  : "# code to insert into target file"); 

Upvotes: 0

ray
ray

Reputation: 159

See: File being used by another process after using File.Create()

Just remove File.Create and directly use:

using (StreamWriter sw = new StreamWriter(path, true))
{
    // ...
}

Upvotes: 0

Related Questions