jobormo
jobormo

Reputation: 144

Can't delete a file "The process cannot access the file"

I have this code, the idea is to read from a file and the delete the file.

                StreamReader sr = new StreamReader(path);

                s = sr.ReadLine();
                if ((s != null))
                {
                 sr.ReadLine();
                  do
                   {
                   // I start to read and get the characters

                   }while (!(sr.EndOfStream));
                 }
                 sr.close();

and then after close the streamReader, I try to delete the file but I can't:

"The process cannot access the file because it is being used by another process"

What can I do?

Upvotes: 1

Views: 3450

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

To read a file line by line try the following:

using (var reader = new StreamReader(path))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // do something with the line that was just read from the file
    }
}

// At this stage you can safely delete the file
File.Delete(path);

or if the file is small you can even load all the lines in memory:

string[] lines = File.ReadAllLines(path);
// Do something with the lines that were read
...
// At this stage you can safely delete the file
File.Delete(path);

Upvotes: 0

Developer
Developer

Reputation: 8636

Why don't you use some thing like this

using (StreamReader sr= new StreamReader(your Path here))
{
    // do your stuff
}

Upvotes: 0

Mike Nakis
Mike Nakis

Reputation: 61959

Try deleting after enclosing your code in a using statement as follows:

using(  StreamReader sr = new StreamReader(path) ) 
{ 
    ...
}

If that does not work either, then some other process has locked your file.

Upvotes: 2

Related Questions