• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6240
  • 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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
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
 
Hamid HassanCommented:
string[] files = Directory.GetFiles(@"C:\temp");
foreach (string file in files)
{
    File.Delete(file);
}
0
 
Hamid HassanCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

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