Neeraj Verma
Neeraj Verma

Reputation: 2334

System IO Exception : the process cannot access the file because it is being used by another process c#

I have seen several post for this problem .I have implemented all suggestion like using flush() , close() method on streamwriter and connection Object,use GC.Collect() to force cleanup,, use using{} to autodispose

I am Doing Simple Get Operation from DB and write to text file ..here is my Code

public void WriteToFile(string ProductName)
{
    //Already Got Data from DB and stored in "ProductName" 

   //saving in File
    if (!File.Exists(path11))
    {
        File.Create(path11);
        StreamWriter tw = new StreamWriter(path11);
        tw.WriteLine(ProductName+"@"+DateTime.Now.ToString());

        tw.Flush();
        tw.Close();
    }
    else if (File.Exists(path11))
    {
        StreamWriter tw = new StreamWriter(path11, true);
        tw.WriteLine(ProductName + "@" + DateTime.Now.ToString());

        tw.Flush();
        tw.Close();
    }

    GC.Collect();
}

Another suggestion I Got is to lock the object ..But I cannot implement it .. Any suggestion would be Helpful

Upvotes: 2

Views: 1272

Answers (2)

Mike Zboray
Mike Zboray

Reputation: 40838

File.Create creates the file and returns an open stream. You don't really need all that logic. Just use new StreamWriter(path11, true) which will create the file if it doesn't exist and append to it if it does. Also using is helpful:

public void WriteToFile(string ProductName)
{
    //Get Data from DB and stored in "ProductName"
    using (var tw = new StreamWriter(path11, true))
    {
        tw.WriteLine(ProductName+"@"+DateTime.Now.ToString());
    }
}

Upvotes: 5

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

FileCreate returns a stream which you should use to instantiate StreamWriter:

var file = File.Create(path11);
StreamWriter tw = new StreamWriter(file);

And you should use using blocks to make sure your stream and file is closed when you're finished writing.

Upvotes: 2

Related Questions