Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# delete files

// Simple synchronous file deletion operations with no user interface.
// To run this sample, create the following files on your drive:
// C:UsersPublicDeleteTest	est1.txt
// C:UsersPublicDeleteTest	est2.txt
// C:UsersPublicDeleteTestSubDir	est2.txt

public class SimpleFileDelete
{
    static void Main()
    {
        // Delete a file by using File class static method...
        if(System.IO.File.Exists(@"C:UsersPublicDeleteTest	est.txt"))
        {
            // Use a try block to catch IOExceptions, to
            // handle the case of the file already being
            // opened by another process.
            try
            {
                System.IO.File.Delete(@"C:UsersPublicDeleteTest	est.txt");
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
        }

        // ...or by using FileInfo instance method.
        System.IO.FileInfo fi = new System.IO.FileInfo(@"C:UsersPublicDeleteTest	est2.txt");
        try
        {
            fi.Delete();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // Delete a directory. Must be writable or empty.
        try
        {
            System.IO.Directory.Delete(@"C:UsersPublicDeleteTest");
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
        // Delete a directory and all subdirectories with Directory static method...
        if(System.IO.Directory.Exists(@"C:UsersPublicDeleteTest"))
        {
            try
            {
                System.IO.Directory.Delete(@"C:UsersPublicDeleteTest", true);
            }

            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        // ...or with DirectoryInfo instance method.
        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:UsersPublicpublic");
        // Delete this dir and all subdirs.
        try
        {
            di.Delete(true);
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
Source by learn.microsoft.com #
 
PREVIOUS NEXT
Tagged: #delete #files
ADD COMMENT
Topic
Name
3+8 =