Search This Blog

Friday, February 11, 2011

Delete file which is already in use using C#.net

Sometime scenario arises where we need to delete a file using C#.
But sometime an error is thrown like "File is already in use. Not able to delete"

Here is the solution to delete that file

if(File.Exists(FullFileName))
{
       GC.Collect();
       GC.WaitForPendingFinalizers();
       FileInfo f = new FileInfo(FullFileName);
       f.Delete();
}

6 comments:

  1. doesn't work for me :(

    ReplyDelete
  2. Can u give me more information about your code implementation.

    ReplyDelete
  3. Try this code

    using System;
    private void button1_Click(object sender, RoutedEventArgs e)
    {
    string FilePath = @"F:\1.txt";
    if (File.Exists(FilePath))
    {
    GC.Collect();
    GC.WaitForPendingFinalizers();
    FileInfo f = new FileInfo(FilePath);
    f.Delete();

    }

    }

    ReplyDelete
  4. Thanks, it works for me.

    ReplyDelete
  5. Tanks for everything

    ReplyDelete
  6. Thanks very much! This helped me tremendously!

    ReplyDelete