Hi All,

Can anybody help me in finding this out?

I want to delete csv file using C#.Net?

I am using:-

File.Delete("E:\TestFolder\filename.csv");
OR

if (System.IO.File.Exists("E:\TestFolder\filename.csv"))
{
   System.IO.File.Delete("E:\TestFolder\filename.csv");
}

But both above are giving exception as:-
Cannot access the file "E:\TestFolder\filename.csv" because it is being used by another process.

Test Folder is a shared folder and I am having full admin rights over the folder.

Your Help is highly appreciated.

Thanks & regards,
Manish

The error is precisely what it says: the file cannot be deleted until all processes have closed it and disposed of any references to it.

I'd suggest downloading and running Process Monitor to find out which process still has a lock on that file. This will give you some direction in how to fix the problem, if the process turns out to be your own. If the process isn't yours, you're SOL and simply need to wait until the file is unlocked.

However, I'm willing to bet that it's your process and that the stream wasn't properly disposed or you didn't give the garbage collector enough time to fully dispose it. First and foremost you need to ensure that any streams or file operations on that file are closed and disposed before trying to delete it. If the problem still occurs, sometimes you need a retry loop as added insurance:

public bool SafeDelete(string path, int retries)
{
    for (i = 0; i < retries; i++)
    {
        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
                return true;
            }
        }
        catch (Exception ex)
        {
            Thread.Sleep(100);

            // Log if desired
        }
    }

    return false;
}

Hi, what is the value of "retries"?

Another point is, if the file is in a shared folder, maby other users are using it. It may be a file important to them. So why delete it on the fly without letting the other users know about it?

Hi, what is the value of "retries"?

Whatever you want, that's why it's a method parameter. I often use 3, though.

But, are you sure that 3 is enough? is that a safe bet? Because stream can take even longer to close.

This would be better:

public bool SafeDelete(string path)
        {
            while (true)
            {
                try
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Thread.Sleep(100);
                    // Log if desired
                }
            }
        }

But, are you sure that 3 is enough?

Reasonably sure. If it takes longer than that, I treat it as an error condition because disposal and unlocking are relatively quick. If disposal and unlocking are known to be slow for some reason, that's an edge case that warrants longer waits (hence adding retries as a method parameter). But under normal circumstances, and in my experience, 3 pauses of 100ms are more than sufficient to let cleanup happen.

This would be better:

No, it wouldn't be. What if the process doesn't have permission to delete files in that directory? You've hung your application in an infinite loop. In that case logging is a necessity because now there's a critical need to troubleshoot the bad behavior.

ok the reason why im asking these questions is because i am experiencing the same thing. I created a service, it deletes files, but every so often, it cannot delete a file.

So my application does have permission to delete, and your method for file delete with my added infinite loop should loop until the condition is true, then application jumps out of that infinite loop and continues with the rest of what its supposed to do.

Is this not a safe bet?

I still feel that 3 seconds is to short for mine.

If you have time, can you take a look at this please?
http://www.daniweb.com/software-development/csharp/threads/458854/deleting-a-file

I created a service, it deletes files, but every so often, it cannot delete a file.

In cases like this, rather than try to find a sweet spot for timing, I'll simply add the failed paths to a collection and retry later during a global cleanup operation. Most likely it's not imperative that these files be deleted immediately, so if they fail due to being in use, it's probably fine to postpone.

I still feel that 3 seconds is to short for mine.

Then use a larger value for retries. Once again, this is precisely why I made it a method parameter instead of hard coding it to 3. 3 has worked for me in the past, but I'm not naive enough to believe that it's the perfect value for all occasions.

Instead of deleting it, would it be best to move the file then delete it?

Instead of deleting it, would it be best to move the file then delete it?

To what end? A move operation ends with deletion of the original file. You'll have similar issues as straight up deletion if the original file is in use.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.