How do I delete an existing file?

Category: System.IO, viewed: 1K time(s).
using System;
using System.IO;

namespace Kodecsharp.Example.System.IO {
    class FileDeleteDemo {
        public static void Main(string[] args) {
            string fileName = @"c:\users\me\demo.txt";

            //
            // To delete a file we can use the File.Delete() method and
            // pass the filename to be deleted as the parameter.
            //
            if (File.Exists(fileName)) {
                File.Delete(fileName);
            }

            //
            // We can also use the FileInfo class's Delete() method to
            // delete a file.
            //
            if (File.Exists(fileName)) {
                FileInfo fi = new FileInfo(fileName);
                fi.Delete();
            }
        }
    }
}
Powered by Disqus