Link to home
Start Free TrialLog in
Avatar of dodgerfan
dodgerfanFlag for United States of America

asked on

Delete all files in a folder - C#

How can you delete all of the files in a directory with ASP.Net/C#?
Avatar of cdaly33
cdaly33
Flag of United States of America image


    Dim files As String() = IO.Directory.GetFiles("path with files to delete")
    For Each file In files
      IO.File.Delete(file)
    Next

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of cdaly33
cdaly33
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

// Delete files on the server:
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Data"));
FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files)
{
    file.Delete();
}
 
// Delete files on the client's machine
// will lead to a serious security breach
// NO GO

Open in new window

cdaly33: your code will cause issues:
string[] files = IO.Directory.GetFiles("path with files to delete");

Gives the error:
Cannot convert source type System.IO.FileInfo[ ] to target type string[ ]

Avatar of Dmitry G
As I understand user needs to have rights to delete. Just in case.

See also other solution:

https://www.experts-exchange.com/questions/23630424/Asp-net-delete-a-file-in-the-server.html
The folder with the files in it needs to have Full Permission granted to NETWORK_SERVICE

Danger Will Robinson...
string[] files = Directory.GetFiles(@"C:\temp");
foreach (string file in files)
{
    File.Delete(file);
}
SOLUTION
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