Showing posts with label Directory. Show all posts
Showing posts with label Directory. Show all posts

Wednesday, November 02, 2011

Delete All Files using C#

For Deleting all the files first you need to get the list of file names from the specified directory (using static method Directory.Get­Files. Then delete all files from the list.
Method 1
using System.IO;

string[] filePaths = Directory.GetFiles(@"c:\Directory\");
foreach (string filePath in filePaths)

Method 2

To Delete all files using one code line, you can use Array.ForEach with combination of anonymous method.

Array.ForEach(Directory.GetFiles(@"c:\MyDirectory\"),delegate(string path) 
{ File.Delete(path); });

C# Checking a File exists in Folder

How to get all files from a folder and compare a whether that file exists in that folder or not. Here is a sample code where you can loop through the code and check the file.

I have declared a variable to check there it exists or not.

private bool isFileExists = false;

Now I have this code to check whether file exists and based on it I’ll redirect in to that page.

string searchfolder = Server.MapPath("~") + "\\TestFolder";
DirectoryInfo Dir = new DirectoryInfo(searchfolder);
FileInfo[] FileList = Dir.GetFiles("*.aspx", SearchOption.AllDirectories);
foreach (FileInfo FI in FileList)
if (FI.Name == redirectPage)
isFileExists = true;
if (isFileExists == true)

Here I have search pattern as *.aspx as I need to check these files. This can be based on the files you want to check