Search This Blog

Saturday 16 July 2016

Delete file in c#

using System.IO;

Delete respective file

string fileName = "test.txt";
string sourcePath = @"C:\Test Folder";
string sourceFile = Path.Combine(sourcePath, fileName);

if (File.Exists(sourceFile))
{
    File.Delete(sourceFile);
}

Delete all files

string sourcePath = @"C:\Test Folder";

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    File.Delete(sourcefile);
}

Delete only .txt extension files

string sourcePath = @"C:\Test Folder";

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    string ext = Path.GetExtension(sourcefile);

    if (ext.Equals(".txt"))
    {
        File.Delete(sourcefile);
    }
}

No comments:

Post a Comment