deleting folder and subfolders in c# - c#

I have a folder that contains sub folders and files with read only attribute (both files and folders). I want to delete this folder with sub-folders and files.
I wrote this code:
static void Main(string[] args)
{
DirectoryInfo mm = new DirectoryInfo(#"c:\ex");
string aa = Convert.ToString(mm);
string[] allFileNames =
System.IO.Directory.GetFiles(aa,
"*.*",
System.IO.SearchOption.AllDirectories);
string[] alldirNames =
System.IO.Directory.GetDirectories(aa,
"*",
System.IO.SearchOption.AllDirectories);
foreach (string filename in allFileNames)
{
FileAttributes attr = File.GetAttributes(filename);
File.SetAttributes(filename, attr & ~FileAttributes.ReadOnly);
}
foreach (string dirname in alldirNames)
{
FileAttributes attr = File.GetAttributes(dirname);
File.SetAttributes(dirname, attr & ~FileAttributes.ReadOnly);
Directory.Delete(dirname , true);
}
FileInfo[] list = mm.GetFiles();
foreach (FileInfo k in list)
{
k.Delete();
}
mm.Delete();
Console.ReadKey();
}
The problem now is that whenever I run the program it gives me the following error:
Could not find a part of the path 'c:\ex\xx\bb'.
What does this error mean?

Directory.Delete(path, true);
Documentation

The previous answer might work, but I believe it will occur with problems in ReadOnly files. But to ensure the deletion and removal of any attribute ReadOnly, the best way to perform this procedure you must be using a method to facilitate the way you were doing, you were not using the correct properties of objects, for example, when using
DirectoryInfo.ToString ()
and use the
DirectoryInfo.GetFiles (aa ...
you were not using the resources the Framework offers within the DirectoryInfo class. See below:
void DirectoryDelete(string strOriginalPath)
{
DirectoryInfo diOriginalPath = new DirectoryInfo(strOriginalPath);
if (diOriginalPath.Attributes.HasFlag(FileAttributes.ReadOnly))
diOriginalPath.Attributes &= ~FileAttributes.ReadOnly;
string[] lstFileList = Directory.GetFiles(strOriginalPath);
string[] lstdirectoryList = Directory.GetDirectories(strOriginalPath);
if (lstdirectoryList.Length > 0)
{
// foreach on the subdirs to the call method recursively
foreach (string strSubDir in lstdirectoryList)
DirectoryDelete(strSubDir);
}
if (lstFileList.Length > 0)
{
// foreach in FileList to be delete files
foreach (FileInfo fiFileInDir in lstFileList.Select(strArquivo => new FileInfo(strArquivo)))
{
// removes the ReadOnly attribute
if (fiFileInDir.IsReadOnly)
fiFileInDir.Attributes &= ~FileAttributes.ReadOnly;
// Deleting file
fiFileInDir.Delete();
}
}
diOriginalPath.Delete();
}

EmptyFolder(new DirectoryInfo(#"C:\your Path"))
Directory.Delete(#"C:\your Path");
private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}

Related

Delete TMP file in a local folder

I have these files in my local folder.
As you can see from the image above, there is a TMP file in it. I don't know how it is generated but I believe it is a useless temp file, so I try to delete it this way:
foreach (var item in await ApplicationData.Current.LocalFolder.GetFilesAsync())
if (item.Name.EndsWith(".TMP"))
await item.DeleteAsync();
However, using neither GetFilesAsync() nor GetItemsAsync() finds the temp file. The former gives me the json files only and the latter finds everything but the tmp file.
How should I find and delete it?
You could use the following code to detect the hidden file where in the sandbox(It only works in sandbox).
public static class ParseDir
{
public static FileInfo[] GetFilesFromDirectory(string DirName, string pattern, bool Recursive)
{
if (!Directory.Exists(DirName))
throw new Exception("No such Directory.");
DirectoryInfo dirInfo = new DirectoryInfo(DirName);
SearchOption Recur = Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return dirInfo.GetFiles(pattern, Recur);
}
public static FileInfo[] GetHiddenOnlyFiles(FileInfo[] Files)
{
List<FileInfo> result = new List<FileInfo>();
foreach (FileInfo file in Files)
if ((file.Attributes & System.IO.FileAttributes.Hidden) == System.IO.FileAttributes.Hidden)
result.Add(file);
return result.ToArray();
}
}
Usage
FileInfo[] filesInS = ParseDir.GetFilesFromDirectory(ApplicationData.Current.LocalFolder.Path, "*.*", false);
FileInfo[] hiddenFiles = ParseDir.GetHiddenOnlyFiles(filesInS);
hiddenFiles.First().Delete();

How can I find a file within any description of path?

I need find the specific file/folder on my hard drive.
For example i need find a file (do1.bat) and then store the path of the file. But i dont know where can it be stored, so i have to scan all hard drive.
How can i use C# for this?
A simple way would be
var results = Directory.GetFiles("c:\\", "do1.bat", SearchOption.AllDirectories);
This would recurse through all directory and collect all files named do1.bat. Unfortunatly this will not work on complete c:\ since it will throw exceptions if you don't have access to a directory, which surely will happen.
So this is a recursive version:
private static void FindFile(DirectoryInfo currentDirectory, string pattern, List<FileInfo> results)
{
try
{
results.AddRange(currentDirectory.GetFiles(pattern, SearchOption.TopDirectoryOnly));
foreach (DirectoryInfo dir in currentDirectory.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => d.Name != "." && d.Name != ".."))
FindFile(dir, pattern, results);
}
catch
{
// probably no access to directory
}
}
This recurses through the directory tree and tries to get the files in a directory and then all subdirectories (except . and ..).
You can use it this way:
DirectoryInfo d = new DirectoryInfo("c:\\");
List<FileInfo> results = new List<FileInfo>();
FindFile(d, "do1.bat", results);
This will find all files named do1.bat in any subdirectory of C:\\ and enlist the FileInfos in the results list.
this should provide you a list of files, matching your search pattern
string[] Result = Directory.GetFiles(#"C:\", "do1.bat", SearchOption.AllDirectories);
Refer: https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx
List<string> lstfilepaths = new List<string>();
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries) // included as per your logic
{
if(fileName == "do1.bat")
{
ProcessFile(fileName);
}
}
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static void ProcessFile(string path)
{
lstfilepaths.Add(path);
}
For one file:
public string FindFileByName(string fileName, string searchPath)
{
string resultPath = null;
DirectoryInfo directoryInWhichToSearch = new DirectoryInfo(searchPath);
FileInfo foundFile = directoryInWhichToSearch.GetFiles(fileName, SearchOption.AllDirectories)[0];
resultPath = foundFile.FullName;
return resultPath;
}
You can then use it like this:
string fileFullPath = FindFileByName("do1.bat", #"C:\");

How to copy more than one folder into another folder?

Now here is the problem:
I have a lot of code that all does the same thing. That is, it copies the contents of two folders into a destination folder and merges them in the destination folder. My problem is, I cannot find out (after much Googling) how to actually copy the source directories + contents as opposed to just its contents and sub folders which then end up merged.
It may be how I'm obtaining the directories: I use a Folder Selection Dialog, add the path name to a listbox (To display) and then create a list of (string) directories from the items in the listbox.
Here is the code so far. (Some is from MSDN)
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.ToLower() == target.FullName.ToLower())
{
return;
}
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into it's new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
//This is inside a button click Method
List<string> pathList = new List<string>();
pathList = lstBox.Items.Cast<String>().ToList();
string sourceDirectory;
string targetDirectory;
DirectoryInfo dirSource;
DirectoryInfo dirTarget;
for (int i = 0 ; i < pathList.Count; i++)
{
sourceDirectory = pathList.ElementAt(i);
targetDirectory = browserSave.SelectedPath; //browserSave is the Folder Selection Dialog
dirSource = new DirectoryInfo(sourceDirectory);
dirTarget = new DirectoryInfo(targetDirectory);
CopyAll(dirSource, dirTarget);
}
Annoyingly C# has no Directory.Copy function which would be extremely useful.
Recap.
I Select Folder 1.
I select Folder 2.
I Select Destination Folder.
I Press OK.
Expected Result: Destination Folder has two folders, Folder 1 and Folder 2 inside. Both has all files inside.
Actual Result: Destination Folder has loose files merged, and sub directories of source folders intact. (Which is whats annoying)
I hope this is enough info for you professionals to help with.
The problem is you are never making a new target for your destination -- this will make a new target with the same name as the source for each iteration of the loop and then copy to that target.
for (int i = 0 ; i < pathList.Count; i++)
{
sourceDirectory = pathList.ElementAt(i);
targetDirectory = browserSave.SelectedPath; //browserSave is the Folder Selection Dialog
dirSource = new DirectoryInfo(sourceDirectory);
string targetPath = target.Fullname+
Path.DirectorySeparatorChar+
sourceDirectory.Split(Path.DirectorySeparatorChar).Last());
Directory.CreateDirectory(targetPath);
dirTarget = new DirectoryInfo(targetPath);
CopyAll(dirSource, dirTarget);
}
caveat I did not test so I might have typos, but you get the idea.
Instead of DirectoryInfo pass string as a parameter. See the code below.
private void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
In main function.
static void Main(string[] args)
{
List<string> directoryNames = new List<string>() // For multiple source folders
{
"C:\\Folder1", "C:\\Folder2"
};
string destDirName = "C:\\Folder3";
foreach (string sourceDirName in directoryNames)
{
DirectoryCopy(sourceDirName, destDirName, true)
}
}
Try the following. You'll obviously need to set the source and destination folders accordingly when you invoke action. Also I would suggest that you do not embed any logic in event handlers.
Hope this helps.
Action<string, string> action = null;
action = (source,dest) =>
{
if(Directory.Exists(source))
{
DirectoryInfo sInfo = new DirectoryInfo(source);
if (!Directory.Exists(dest))
{
Directory.CreateDirectory(dest);
}
Array.ForEach(sInfo.GetFiles("*"), a => File.Copy(a.FullName, Path.Combine(dest,a.Name)));
foreach (string dir in Directory.EnumerateDirectories(source))
{
string sSubDirPath = dir.Substring(source.Length+1,dir.Length-source.Length-1);
string dSubDirPath = Path.Combine(dest,sSubDirPath);
action(dir, dSubDirPath);
}
}
};
action(#"C:\source", #"C:\dest");
This will help you to solve your problem.This function is a generic recursive function for copy folder with or not sub folders with merging.
public static void DirectoryCopy(string sourceDirPath, string destDirName, bool isCopySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirPath);
DirectoryInfo[] directories = directoryInfo.GetDirectories();
if (!directoryInfo.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: "
+ sourceDirPath);
}
DirectoryInfo parentDirectory = Directory.GetParent(directoryInfo.FullName);
destDirName = System.IO.Path.Combine(parentDirectory.FullName, destDirName);
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = System.IO.Path.Combine(destDirName, file.Name);
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
file.CopyTo(tempPath, false);
}
// If copying subdirectories, copy them and their contents to new location using recursive function.
if (isCopySubDirs)
{
foreach (DirectoryInfo item in directories)
{
string tempPath = System.IO.Path.Combine(destDirName, item.Name);
DirectoryCopy(item.FullName, tempPath, isCopySubDirs);
}
}
}

Delete all files and folders in multiple directory but leave the directoy

Well I like this nice piece of code right here it seems to work awesomely but I can't seem to add any more directories to it
DirectoryInfo dir = new DirectoryInfo(#"C:\temp");
foreach(FileInfo files in dir.GetFiles())
{
files.Delete();
}
foreach (DirectoryInfo dirs in dir.GetDirectories())
{
dirs.Delete(true);
}
I would also like to add in special folders as well like History and cookies and such how would I go about doing that (I would like to include at least 4-5 different folders)
Perhaps something like this would help. I did not test it.
public void DeleteDirectoryFolders(DirectoryInfo dirInfo){
foreach (DirectoryInfo dirs in dirInfo.GetDirectories())
{
dirs.Delete(true);
}
}
public void DeleteDirectoryFiles(DirectoryInfo dirInfo) {
foreach(FileInfo files in dirInfo.GetFiles())
{
files.Delete();
}
}
public void DeleteDirectoryFilesAndFolders(string dirName) {
DirectoryInfo dir = new DirectoryInfo(dirName);
DeleteDirectoryFiles(dir)
DeleteDirectoryFolders(dir)
}
public void main() {
List<string> DirectoriesToDelete;
DirectoriesToDelete.add("c:\temp");
DirectoriesToDelete.add("c:\temp1");
DirectoriesToDelete.add("c:\temp2");
DirectoriesToDelete.add("c:\temp3");
foreach (string dirName in DirectoriesToDelete) {
DeleteDirectoryFilesAndFolders(dirName);
}
}
Here's a recursive function that will delete all files in a given directory and navigate down the directory structure. A pattern string can be supplied to only work with files of a given extension, as per your comment to another answer.
Action<string,string> fileDeleter = null;
fileDeleter = (directoryPath, pattern) =>
{
string[] files;
if (!string.IsNullOrEmpty(pattern))
files = Directory.GetFiles(directoryPath, pattern);
else
files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
File.Delete(file);
}
string[] directories = Directory.GetDirectories(directoryPath);
foreach (string dir in directories)
fileDeleter(dir, pattern);
};
string path = #"C:\some_folder\";
fileDeleter(path, "*.bmp");
Directories are otherwise left alone, and this can obviously be used with an array or list of strings to work with multiple initial directory paths.
Here is the same code rewritten as a standard function, also with the recursion as a parameter option.
public void DeleteFilesFromDirectory(string directoryPath, string pattern, bool includeSubdirectories)
{
string[] files;
if (!string.IsNullOrEmpty(pattern))
files = Directory.GetFiles(directoryPath, pattern);
else
files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
File.Delete(file);
}
if (includeSubdirectories)
{
string[] directories = Directory.GetDirectories(directoryPath);
foreach (string dir in directories)
DeleteFilesFromDirectory(dir, pattern, includeSubdirectories);
}
}

How do I delete a directory with read-only files in C#?

I need to delete a directory that contains read-only files. Which approach is better:
Using DirectoryInfo.Delete(), or,
ManagementObject.InvokeMethod("Delete")?
With DirectoryInfo.Delete(), I have to manually turn off the read-only attribute for each file, but ManagementObject.InvokeMethod("Delete") doesn't appear to need to. Is there any situation where one is more preferable to the other?
Sample code (test.txt is read only).
First way:
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\David\Desktop\");
dir.CreateSubdirectory("Test");
DirectoryInfo test = new DirectoryInfo(#"C:\Users\David\Desktop\Test\");
File.Copy(#"C:\Users\David\Desktop\test.txt", #"C:\Users\David\Desktop\Test\test.txt");
File.SetAttributes(#"C:\Users\David\Desktop\Test\test.txt", FileAttributes.Archive);
test.Delete(true);
Second way:
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\David\Desktop\");
dir.CreateSubdirectory("Test");
DirectoryInfo test = new DirectoryInfo(#"C:\Users\David\Desktop\Test\");
File.Copy(#"C:\Users\David\Desktop\test.txt", #"C:\Users\David\Desktop\Test\test.txt");
string folder = #"C:\Users\David\Desktop\Test";
string dirObject = "Win32_Directory.Name='" + folder + "'";
using (ManagementObject managementObject = new ManagementObject(dirObject))
{
managementObject.Get();
ManagementBaseObject outParams = managementObject.InvokeMethod("Delete", null,
null);
// ReturnValue should be 0, else failure
if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0)
{
}
}
Simplest way of avoiding recursive calls is by utilising the AllDirectories option when getting FileSystemInfos, like so:
public static void ForceDeleteDirectory(string path)
{
var directory = new DirectoryInfo(path) { Attributes = FileAttributes.Normal };
foreach (var info in directory.GetFileSystemInfos("*", SearchOption.AllDirectories))
{
info.Attributes = FileAttributes.Normal;
}
directory.Delete(true);
}
Here is an extension method which sets Attributes to Normal recursively, then deletes the items:
public static void DeleteReadOnly(this FileSystemInfo fileSystemInfo)
{
var directoryInfo = fileSystemInfo as DirectoryInfo;
if (directoryInfo != null)
{
foreach (FileSystemInfo childInfo in directoryInfo.GetFileSystemInfos())
{
childInfo.DeleteReadOnly();
}
}
fileSystemInfo.Attributes = FileAttributes.Normal;
fileSystemInfo.Delete();
}
Try this,
private void DeleteRecursiveFolder(string pFolderPath)
{
foreach (string Folder in Directory.GetDirectories(pFolderPath))
{
DeleteRecursiveFolder(Folder);
}
foreach (string file in Directory.GetFiles(pFolderPath))
{
var pPath = Path.Combine(pFolderPath, file);
FileInfo fi = new FileInfo(pPath);
File.SetAttributes(pPath, FileAttributes.Normal);
File.Delete(file);
}
Directory.Delete(pFolderPath);
}
Another method without the need for recursion.
public static void ForceDeleteDirectory(string path)
{
DirectoryInfo root;
Stack<DirectoryInfo> fols;
DirectoryInfo fol;
fols = new Stack<DirectoryInfo>();
root = new DirectoryInfo(path);
fols.Push(root);
while (fols.Count > 0)
{
fol = fols.Pop();
fol.Attributes = fol.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
foreach (DirectoryInfo d in fol.GetDirectories())
{
fols.Push(d);
}
foreach (FileInfo f in fol.GetFiles())
{
f.Attributes = f.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
f.Delete();
}
}
root.Delete(true);
}
private void DeleteRecursiveFolder(DirectoryInfo dirInfo)
{
foreach (var subDir in dirInfo.GetDirectories())
{
DeleteRecursiveFolder(subDir);
}
foreach (var file in dirInfo.GetFiles())
{
file.Attributes=FileAttributes.Normal;
file.Delete();
}
dirInfo.Delete();
}
The best solution is to mark all the files as non-read only, and then delete the directory.
// delete/clear hidden attribute
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.Hidden);
// delete/clear archive and read only attributes
File.SetAttributes(filePath, File.GetAttributes(filePath)
& ~(FileAttributes.Archive | FileAttributes.ReadOnly));
Notice that ~ is a Bitwise logical operator which returns the complement of the given binary value. I haven't tested this, but it should work.
Thanks!
I would say that your first approach looks more explicit and readable. The second method smells like reflection, is not type safe and looks weird. The ManagementObject can represent multiple things, so it's not obvious that .InvokeMethod("Delete") actually deletes a directory.
On the surface, using the WMI approach seems more efficient than iterating over the entire file system (assume for example the directory has 10's of thousands of files). But I do not know that WMI also doesn't do iterations. If it does, being closer to the metal (again, assumptions) it should be more efficient.
For elegance, I concede the recursive method is cool.
Performance testing should answer the efficiency question. And either can be elegant if wrapped in an extension method of DirectoryInfo.
Here is another solution that avoids recursion on itself.
public static void DirectoryDeleteAll(string directoryPath)
{
var rootInfo = new DirectoryInfo(directoryPath) { Attributes = FileAttributes.Normal };
foreach (var fileInfo in rootInfo.GetFileSystemInfos()) fileInfo.Attributes = FileAttributes.Normal;
foreach (var subDirectory in Directory.GetDirectories(directoryPath, "*", SearchOption.AllDirectories))
{
var subInfo = new DirectoryInfo(subDirectory) { Attributes = FileAttributes.Normal };
foreach (var fileInfo in subInfo.GetFileSystemInfos()) fileInfo.Attributes = FileAttributes.Normal;
}
Directory.Delete(directoryPath, true);
}
This works by resettings attributes on the folders and files before the delete, so you could just remove the last line for a 'DirectoryResetAttributes' method and use delete separately.
On a related note, while this worked, I then had issues with deleting paths that were 'too long' and ended up using a robocopy solution posted here: C# deleting a folder that has long paths
To follow up on Vitaliy Ulantikov's solution I have supplemented it with a rename/move folder method:
public static void renameFolder(String sourcePath, String targetPath) {
try
{
if (System.IO.Directory.Exists(targetPath))
DeleteFileSystemInfo(new DirectoryInfo(targetPath));
System.IO.Directory.Move(sourcePath, targetPath);
}
catch (Exception ex)
{
Console.WriteLine("renameFolder: " + sourcePath + " " + targetPath + " " + ex.Message);
throw ex;
}
}
private static void DeleteFileSystemInfo(FileSystemInfo fsi) {
fsi.Attributes = FileAttributes.Normal;
var di = fsi as DirectoryInfo;
if (di != null)
{
foreach (var dirInfo in di.GetFileSystemInfos())
{
DeleteFileSystemInfo(dirInfo);
}
}
fsi.Delete();
}
My solution for NET framework 3.5 and for NET framework version 4 and higher:
#region DeleteWithReadOnly
internal static void DeleteWithReadOnly(this DirectoryInfo di)
{
foreach (FileSystemInfo fsi in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
{
fsi.Attributes = FileAttributes.Normal;
}
di.Delete(true);
}
#endregion
#region DeleteWithReadOnlyNET3_5
internal static void DeleteWithReadOnlyNET3_5(this DirectoryInfo di)
{
foreach (FileSystemInfo fsi in di.GetFiles("*", SearchOption.AllDirectories))
{
fsi.Attributes = FileAttributes.Normal;
}
di.Delete(true);
}
#endregion
Usage:
DirectoryInfo di = new DirectoryInfo(#"C:\TMP");
di.DeleteWithReadOnly();

Categories

Resources