What is the best way to empty a directory? - c#

Is there a way to delete all files & sub-directories of a specified directory without iterating over them?
The non elegant solution:
public static void EmptyDirectory(string path)
{
if (Directory.Exists(path))
{
// Delete all files
foreach (var file in Directory.GetFiles(path))
{
File.Delete(file);
}
// Delete all folders
foreach (var directory in Directory.GetDirectories(path))
{
Directory.Delete(directory, true);
}
}
}

How about System.IO.Directory.Delete? It has a recursion option, you're even using it. Reviewing your code it looks like you're trying to do something slightly different -- empty the directory without deleting it, right? Well, you could delete it and re-create it :)
In any case, you (or some method you use) must iterate over all of the files and subdirectories. However, you can iterate over both files and directories at the same time, using GetFileSystemInfos:
foreach(System.IO.FileSystemInfo fsi in
new System.IO.DirectoryInfo(path).GetFileSystemInfos())
{
if (fsi is System.IO.DirectoryInfo)
((System.IO.DirectoryInfo)fsi).Delete(true);
else
fsi.Delete();
}

Why is that not elegant? It's clean, very readable and does the job.

Well, you could always just use Directory.Delete....
http://msdn.microsoft.com/en-us/library/aa328748%28VS.71%29.aspx
Or if you want to get fancy, use WMI to delete the directory.

Here's an extension method based on the OPs original code, which I think is just fine and a bit more readable than other options.
I agree it would be nice to have a single method in the framework to delete the contents of a directory without deleting the directory, but in my opinion, this is the next best thing.
using System;
using System.IO;
namespace YourNamespace
{
public static class DirectoryInfoExtensions
{
public static void EmptyDirectory(this DirectoryInfo di)
{
if (di.Exists)
{
foreach (var file in di.GetFiles())
{
file.Delete();
}
foreach (var directory in di.GetDirectories())
{
directory.Delete(true);
}
}
}
}
}

Related

c# Unauthorized exception

Hey guys I got this error I have tried to run program as administrator, no luck still get this error I don't get why it can't clean the shortcuts in the recent documents folder, this is my code:
//this will delete the the files in the Recent Documents directory
private void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach(FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
recentDocumentsFolder.Delete();
}
}
//catch any possible error and display a message
catch(Exception)
{
MessageBox.Show("Error could not clean Recent documents directory, please try again");
}
}
I call this method above but dw bout that too much its just calling the method and parameter is the directory. If you want I can post that to.
According to MSDN, FileInfo.Delete() will throw UnauthorizedAccessException when
Source
In order to delete all the files in a directory could do
foreach (string filePath in Directory.GetFiles(recentDocumentsFolder))
{
File.Delete(filePath);
}
If you want to delete the entire directory and any files and subfolders within it you could call
Directory.Delete(recentDocumentsFolder, true);
Your code work for me without any exception, I have select recent document folder using this way and work perfect
System.Environment.GetFolderPath(Environment.SpecialFolder.Recent)
here is my test solution using console application
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string rd = System.Environment.GetFolderPath(Environment.SpecialFolder.Recent);
DeleteRecentDocuments(rd);
Console.ReadLine();
}
//this will delete the the files in the Recent Documents directory
private static void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach (FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
recentDocumentsFolder.Delete();
}
}
//catch any possible error and display a message
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Update
some files inside that directory is protected not only for delete but also copy so you can't delete them but most of others can be delete using below code, I have tested
private static void DeleteRecentDocuments(string RecentDocumentsDirectory)
{
//this is the directory and parameter which we will pass when we call the method
DirectoryInfo cleanRecentDocuments = new DirectoryInfo(RecentDocumentsDirectory);
//try this code
try
{
//loop through the directory we use the getFiles method to collect all files which is stored in recentDocumentsFolder variable
foreach (FileInfo recentDocumentsFolder in cleanRecentDocuments.GetFiles())
{
//we delete all files in that directory
File.Delete(RecentDocumentsDirectory + recentDocumentsFolder);
}
}
//catch any possible error and display a message
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Hope this will help you

How to get a list of files and folders in the subdirectory

I need to get a list of files and folders in a subdirectory.
The file list all clear, but what about a list of directories not sure
using System;
using System.IO;
namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dir = new DirectoryInfo(#"D:\Temp");
Console.WriteLine("============ list of directories =============");
foreach (var item in dir.GetDirectories())
{
Console.WriteLine(item.Name);
Console.WriteLine("== list of subdirectories ==");
foreach (var it in item.GetDirectories())
Console.WriteLine(it.Name);
Console.WriteLine();
}
Console.WriteLine("============== list of files ==============");
foreach (var item in dir.GetFiles())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
}
There is a better way?
Example of directories:
folder1
- folder2
-- folder3
-- folder4
--- folder5
As #Mitch Wheat suggested, there is the option SearchOption.AllDirectories. However, be aware that this may result in an UnauthorizedAccessException when it hits folders which it cannot access.
So the best solution for me always was to use a recursive function which can ignore inaccessible folders.
For a recursive solution, see Ignore folders/files when Directory.GetFiles() is denied access here on StackOverflow or Folder recursion

C# load folder names

I would like my program to read sub-folders from folder in my solution, but i don't know how to read folder names. I can only find, how to read file names and this is not hard to get to work, but with folders, this doesn't seem to work the same way.
Basically I want to load from "Paevik" (2) sub-folders.
E: I forgot to mention, that I want that list into my comboBox
There is System.IO.Directory.EnumerateDirectories(string Path)-method. It returns a collections with directories. Example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
try
{
string dirPath = #"\\archives\2009\reports";
List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
foreach (var dir in dirs)
{
Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));
}
Console.WriteLine("{0} directories found.", dirs.Count);
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
See MSDN.
Try DirectoryInfo.EnumerateDirectories Method
http://msdn.microsoft.com/en-us/library/dd413235.aspx
You can use "GetDirectories" to retrieve an array containing full names of all subdirectories.
string[] subdirectories = Directory.GetDirectories("Full path of your parent folder");
See sample on MSDN page.

C# class to check if files exists in folder

I am very new to C# and i have written the following class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PrinterManager
{
class CheckFilesExist
{
public class CheckFilesExist
{
public static bool check(bool isThere)
{
DirectoryInfo di = new DirectoryInfo("c:\temp");
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length == 0)
{
return isThere;
}
foreach (var fi in TXTFiles)
//return (fi.Exists);
return (fi.Exists);
return check;
}
}
}
}
It should check the directory for *.xml files and add them to an array. If it doesnt find any files then it should return false. It will go through the array and return true or false based on "check".
But i am getting the following error:
Cannot convert method group 'check' to non-delegate type 'bool'. Did
you intend to invoke the method?
It doesnt seem to like, "return check;" at the end.
I basically want to return a check to see if files exists in the folder.
Any ideas why mine isnt working?
Thanks
You can make a one-liner out of your method:
return new DirectoryInfo(#"c:\temp").EnumerateFiles("*.xml").Any();
Note that you are either have to use a literal string (prefixed by #) or properly escape the directory name, i.e. "C:\\temp".
No, it doesn't like return check; at the end - what did you want it to do? Your method is check - so "return true or false based on check" doesn't really make sense. Did you actually mean to return isThere instead?
It's not clear what the parameter is even really meant to be there for, to be honest... and if you've asked a DirectoryInfo for the files in that directory, I'd personally expect them to exist - otherwise why would they be returned?
Oh, and your directory name contains a tab where I suspect you actually want a backslash followed by a t.
I suspect your method would be better as:
public static bool TempDirectoryContainsXmlFiles()
{
DirectoryInfo di = new DirectoryInfo(#"c:\temp");
return di.GetFiles("*.xml").Length > 0;
}
or using LINQ for clarity:
public static bool TempDirectoryContainsXmlFiles()
{
DirectoryInfo di = new DirectoryInfo(#"c:\temp");
return di.GetFiles("*.xml").Any();
}
(You can use EnumerateFiles as shown by BrokenGlass which is more efficient for a large directory, but it's only available in .NET 4 and upwards.)
At a first glance, the problem as to be with the fact of your "check" variable having the same name as your function...
try like this....
private static bool Check_file_Existence(string sFileName)
{
try
{
return File.Exists(sFileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}

How to delete subdirectories

Lets say a have some path:
C:\Temp\TestFolder1\TestFolder2
And I have some template:
C:\Temp
So I want to write function that will delete all subdirectories by template
void DeleteSubdirectories(string tlt, string path) {}
If I call this function with given parameters
DeleteSubdirectories("C:\Temp", "C:\Temp\TestFolder1\TestFolder2");
It must delete TestFolder1\TestFolder2 subdirectories from 'C:\Temp
What is the best way to write this function?
If you desire to delecte "C:\Temp" too, use this:
System.IO.Directory.Delete(#"C:\Temp", true);
If you just want to delete the sub directories use this:
foreach (var subDir in new DirectoryInfo(#"C:\Temp").GetDirectories()) {
subDir.Delete(true);
}
System.IO.Directory.Delete("Path", true);
Just use Directory.Delete - the overload I linked has a boolean value that indicates if subdirectories should also be deleted.
What you're describing sounds wierd, but try this:
using System;
using System.IO;
static void DeleteSubDirectories(string rootDir, string childPath)
{
string fullPath = Path.Combine(rootDir, childPath);
Directory.Delete(fullPath);
string nextPath = Path.GetDirectoryName(fullPath);
while (nextPath != rootDir)
{
Directory.Delete(nextPath);
nextPath = Path.GetDirectoryName(nextPath);
}
}
Use it like:
DeleteSubdirectories("C:\Temp", "TestFolder1\TestFolder2");
Obviously, you'll have to implement the exception handling.

Categories

Resources