The process cannot access the file because it is being used by another process (File is created but contains nothing)

149,196

Solution 1

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

Solution 2

You are writing to the file prior to closing your filestream:

using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
   str.BaseStream.Seek(0,SeekOrigin.End); 
   str.Write("mytext.txt.........................");
   str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
   string addtext="this line is added"+Environment.NewLine;

   str.Flush();

}

File.AppendAllText(path,addtext);  //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);

The above code should work, using the methods you are currently using. You should also look into the using statement and wrap your streams in a using block.

Solution 3

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

Share:
149,196
Admin
Author by

Admin

Updated on September 08, 2020

Comments

  • Admin
    Admin over 3 years
    using System.IO;
    
    class test
    {
        public static void Main()
        {
    
            string path=@"c:\mytext.txt";
    
            if(File.Exists(path))
            {
                File.Delete(path);
            }
    
    
            FileStream fs=new FileStream(path,FileMode.OpenOrCreate);
            StreamWriter str=new StreamWriter(fs);
            str.BaseStream.Seek(0,SeekOrigin.End); 
            str.Write("mytext.txt.........................");
            str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
            string addtext="this line is added"+Environment.NewLine;
            File.AppendAllText(path,addtext);  //Exception occurrs ??????????
            string readtext=File.ReadAllText(path);
            Console.WriteLine(readtext);
            str.Flush();
            str.Close();
    
            Console.ReadKey();
      //System.IO.IOException: The process cannot access the file 'c:\mytext.txt' because it is //being used by another process.
      // at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
    
        }
    }
    
  • Admin
    Admin over 10 years
    Thanks Buddy ! It Works !
  • Admin
    Admin over 10 years
    Thank You for explaining the logic !
  • Matt  Watson
    Matt Watson over 5 years
    You should try and add some more information to this answer. Why does your code fix the original issue?