the process cannot access the file because it is being used by another process C#

MisterNick

Registered Member
Joined
Oct 22, 2014
Messages
80
Reaction score
61
Hello guys,

I'm trying to create a file if it's not exists and then write some string to it.But i'm getting an error message "the process cannot access the file because it is being used by another process".

if (File.Exists(file))
{
}
else { File.Create(file);

File.SetAttributes(file, FileAttributes.Hidden);
using (StreamWriter writer = new StreamWriter(file, true))
{
writer.Write("3600");
writer.Close();
}
}

Once program will create the file now it's time to write something to the file.And when program is on writing function it's showing an error message
 
First of all how about you revert your logic in say !File.Exists(file) so that you don't have to have that werid empty block (unless you were meant to put something there then it is understandable).

Second assign the File.Create(file) to a variable so you can close and dispose the instance of that down below.
 
Try to set the attribute to hidden after the writing logic.

if (File.Exists(file)) {
File.Create(file);
using (StreamWriter writer = new StreamWriter(file, true))
{
writer.Write("3600");
writer.Close();
}
File.SetAttributes(file, FileAttributes.Hidden);
else {
Console.WriteLine("{0} does not exists", file);
}
 
whats wrong with
Code:
File.WriteAllText(filepath, contents);

also your code is wrong

Code:
using (StreamWriter writer = new StreamWriter(file, true))
{
  writer.Write("3600");
  writer.Close();
}

writer.close is not need as you have the using statement, doubt that is causing the issue, but...



Another way would be to use a lock, have a static object that you can assign a lock to, then any time you want to access the file, lock it, if the file is in use, the lock will pause the execution of the code

Code:
static object locker = new object();

.
..
...
...

lock(locker){
  //all the code you want to do on the file
}
 
Your problem is this:

Code:
if (File.Exists(file))
            {
            }
            else { File.Create(file); }

change it to this
Code:
if (File.Exists(file))
            {
            }
            else { File.Create(file).Close(); }
 
this is the correct code :)
if (File.Exists(file)) {
using (StreamWriter writer = new StreamWriter(file, true))
{
writer.Write("3600");
}
else {
Console.WriteLine("{0} does not exists", file);
}
 
Chdead not really - if file doesn't exist it doesn't create it
 
try
Code:
var enc = Encoding.ASCII;
if (File.Exists(file))
{
   writer = new StreamWriter(new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.None, 4096, FileOptions.None), enc);
}
else
{
   writer = new StreamWriter(new FileStream(file, FileMode.Create, FileAccess.ReadWrite), enc);
}
 
Back
Top