Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6212
  • Last Modified:

Delete all files in a folder - C#

How can you delete all of the files in a directory with ASP.Net/C#?
0
dodgerfan
Asked:
dodgerfan
  • 2
  • 2
  • 2
  • +2
2 Solutions
 
cdaly33Commented:

    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

0
 
cdaly33Commented:
Now in c# as requested.
string[] files = IO.Directory.GetFiles("path with files to delete");
    foreach (var file in files) {
        IO.File.Delete(file);
    }

Open in new window

0
 
nmarunCommented:

// 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

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
nmarunCommented:
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[ ]

0
 
anarki_jimbelCommented:
As I understand user needs to have rights to delete. Just in case.

See also other solution:

http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_23630424.html
0
 
williamcampbellCommented:
The folder with the files in it needs to have Full Permission granted to NETWORK_SERVICE

Danger Will Robinson...
0
 
coagantusCommented:
string[] files = Directory.GetFiles(@"C:\temp");
foreach (string file in files)
{
    File.Delete(file);
}
0
 
coagantusCommented:
Delete all files:

using System.IO;

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

OR

Delete all files (one-row example):

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

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now