Wednesday, July 3, 2013

Avoid insertion of duplicate images using asp.net fileupload




if (fup.HasFile)
        {
            string filename = Path.GetFileName(fup.FileName);
            string image1 = Server.MapPath("images/" + filename);
            if (File.Exists(image1))
            {
                File.Delete(image1);
            }
            fup.SaveAs(image1);
        }





How to delete files from folder

Code:
string[] files = Directory.GetFiles(Server. MapPath(“Foldername”);
foreach (string file in files)
{
    File.Delete(file);
}

Another way:
foreach (var file in Directory.GetFiles(Server.MapPath(“foldername”)))
{
       File.Delete(file);
}

Another way (Lambda Expression):
Array.ForEach(Directory.GetFiles(path), File.Delete);

To Check if the Folder contain any files:
if (Directory.GetFiles(Server.MapPath("Imagefolder"), "*.jpg").Any())
  {
  Array.ForEach(Directory.GetFiles(Server.MapPath("Imagefolder"), "*.jpg"),  File.Delete);
  }