File deletion is forced even if it is used by another process


I am developing an application that requires deleting a file, regardless of whether it is being used by another process.

Consider the following code snippet.

using System;
using System.IO;

namespace DotNet_Concepts.File_Operation
{
    class Deleting_File_Which_Is_In_Use
    {
        static void Main(string[] args)
        {
            StreamReader lclFileStream = null;
            string lclFileName=string.Empty;
            try
            {
                lclFileName=@"E:\Visual Studio 2008 Projects\DotNet Concepts\DotNet Concepts\Local Files\Garbage.txt";
                if (File.Exists(lclFileName))
                {
                    lclFileStream = new StreamReader(lclFileName);
                    if (lclFileStream != null)
                    {
                        //Doing some operation
                    }
                    //Deleting the file before closing the stream
                    File.Delete(lclFileName);
                }
            }
            catch (Exception ex)
            {

                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();
        }
    }
}

I delete the file that is used by the same process. Is it possible to delete a file

Thank you Amit Shah

+5
source share
3 answers

, Windows, " ". , , , CloseHandle(), . , . , .

Denial Of Service, , . , , . . WriteFile() .

, , . , . , , .

, - . , . , , .

+6
using System.Collections;
using System.Diagnostics;
using System.Management;

if (File.Exists(@"D:\New folder\Test0001.wav"))
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    FileInfo f = new FileInfo(@"D:\New folder\Test0001.wav");
    f.Delete();
}
+2

I delete the file that is used by the same process

First close the file ...

+1
source

All Articles