madmare
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
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
System.IO.Directory.Delete (stringpat h,bool )
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.GetF iles(path) [0]);
deleted = true;
}
return deleted ? 1 : 0;
}
using System.IO;
public int DeleteFromDirectory(string
{
bool deleted = false;
while (Directory.GetFiles(path).
{
File.Delete(Directory.GetF
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;
}
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.