Link to home
Start Free TrialLog in
Avatar of madmare
madmareFlag for Israel

asked on

Delete Files in folder

Hi,
 I need a function that get as parameter a Folder path name and deletes all the files in this folder.

it's 0 if it deleted every thins else it's returns 1


thanks
Avatar of sabeesh
sabeesh
Flag of United States of America image

System.IO.Directory.Delete(stringpath,bool )
Avatar of muzzy2003
muzzy2003

That will delete the directory as well, not what was wanted. Try this:

using System.IO;

public int DeleteFromDirectory(string path)
{
    bool deleted = false;
    while (Directory.GetFiles(path).Count > 0)
    {
        File.Delete(Directory.GetFiles(path)[0]);
        deleted = true;
    }
    return deleted ? 1 : 0;
}
Swap the 1 and 0 - sorry!
Altenative, using exception handling:

using System.IO;
...
public int DeleteFiles(string dirPath)
{
      bool allDeleted = true;
      foreach (string filePath in Directory.GetFiles(dirPath))
      {
            try
            {
                  File.Delete(filePath);
            }
            catch
            {
                  allDeleted = false;
            }
      }
      return allDeleted? 0 : 1;
}
ASKER CERTIFIED SOLUTION
Avatar of strickdd
strickdd
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial