delete folder/files and subfolder - c#

I want to delete a folder containing files and a subfolder, also containing files. I have used everything, but it is not working for me. I'm using the following function in my web-application asp.net:
var dir = new DirectoryInfo(folder_path);
dir.Delete(true);
Sometimes it deletes a folder, or sometimes it doesn't. If a subfolder contains a file, it only deletes the file, and not the folder as well.

Directory.Delete(folder_path, recursive: true);
would also get you the desired result and a lot easier to catch errors.

This looks about right: http://www.ceveni.com/2008/03/delete-files-in-folder-and-subfolders.html
//to call the below method
EmptyFolder(new DirectoryInfo(#"C:\your Path"))
using System.IO; // dont forget to use this header
//Method to delete all files in the folder and subfolders
private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}

The easiest way in my experience is this
Directory.Delete(folderPath, true);
But I am experiencing a problem with this function in a scenario when I am trying to create the same folder right after its deletion.
Directory.Delete(outDrawableFolder, true);
//Safety check, if folder did not exist create one
if (!Directory.Exists(outDrawableFolder))
{
Directory.CreateDirectory(outDrawableFolder);
}
Now when my code tries to create some file in the outDrwableFolder it ends up in exception. like for instance creating image file using api Image.Save(filename, format).
Somehow this piece of helper function works for me.
public static bool EraseDirectory(string folderPath, bool recursive)
{
//Safety check for directory existence.
if (!Directory.Exists(folderPath))
return false;
foreach(string file in Directory.GetFiles(folderPath))
{
File.Delete(file);
}
//Iterate to sub directory only if required.
if (recursive)
{
foreach (string dir in Directory.GetDirectories(folderPath))
{
EraseDirectory(dir, recursive);
}
}
//Delete the parent directory before leaving
Directory.Delete(folderPath);
return true;
}

You can also do the same by using the DirectoryInfo instance method. I just faced this problem and I believe this can resolve your problem too.
var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);
System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
deleteTheseFiles.Delete(true);
For more details have a look at this link as it looks like the same.

I use the Visual Basic version because it allows you to use the standard dialogs.
https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx

Directory.Delete(path,recursive:true);
this code works for delete folder with N subfolder and files in it.

Related

Trouble deleting a folder full of files

This should be very simple but I'm not sure what's wrong. I'm trying to delete all the files in a folder using File.Delete.
This is what I have so far:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var File in ImageFolder.GetFiles())
{
File.Delete(File.FullName);
}
Then the ".Delete" becomes underlined and says no overload for method delete takes 1 argument.
Any help is appreciated.
What you're seeing is called Namespace Ambiguity.
In your own code or a reference DLL you probably have a method called Delete in a Class called File that doesn't support a single string parameter.
To fix the problem fully qualify File.Delete with System.IO, eg:
System.IO.File.Delete
To delete folder full of file use:
Directory.Delete(string directoryName, bool recursive);
https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx
Or from your code above, use:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var fileInfo in ImageFolder.GetFiles())
{
fileInfo.Delete(); //this is FileInfo.Delete
// or
// File.Delete(fileInfo.FullName);
// dont use reserve "File" as your variable name
}
Remember, you are calling FileInfo, not File
You have to change the naming of the variable:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var file in ImageFolder.GetFiles())
{
File.Delete(file.FullName);
}

How to delete the non empty directory in treeview using c#

I am using the TreeView to show directory structures and I need to be able to delete non empty folders.
System.IO.Directory.Delete(TreeView1.SelectedNode.FullPath);
The above code works fine for deleting empty folders, but I need to delete non empty folders, too.
The Directory.Delete method takes an optional second boolean parameter which indicates if you want to delete its contents. Just add true as the second parameter:
System.IO.Directory.Delete(TreeView1.SelectedNode.FullPath, true);
you need to check if directory is empty or not ?
if (Directory.GetFiles(TreeView1.SelectedNode.FullPath).Count() > 0)
{
Directory.Delete(TreeView1.SelectedNode.FullPath, true);
}
To delete folders, files with sub-folders, try this
private void DeleteDirectory(string path)
{
if (Directory.Exists(path))
{
//Delete all files from the Directory
foreach (string file in Directory.GetFiles(path))
{
File.Delete(file);
}
//Delete all child Directories
foreach (string directory in Directory.GetDirectories(path))
{
DeleteDirectory(directory);
}
//Delete a Directory
Directory.Delete(path);
}
}
Call
string path = "yourPath";
DeleteDirectory(path);

C# merge one directory with another

I have an autoupdater C# program. It will download a rar file that holds the changed or new files for the update to some software. The rar file has it's structure just like the base directory of the software but only contains changed or new files/folders. Is there an easy way to "merge" these files/folders to the destination directory so in that if the file/folder exists already it'll be replaced and if not it'll be added or do I have to manually walk through each file/folder and do this myself? Just hoping there is a nice little merge function that .NET has :)
DirectoryInfo Class
The following example demonstrates how to copy a directory and its contents.
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())
{
Console.WriteLine(#"Copying {0}\{1}", target.FullName, fi.Name);
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);
}
}
The simplest way is to use the FileSystem.MoveDirectory method. Make sure you add a reference to the Microsoft.VisualBasic.dll:
using Microsoft.VisualBasic.FileIO;
...
// Merge D:\SourceDir with D:\DestDir:
FileSystem.MoveDirectory("D:\\SourceDir", "D:\\DestDir", true /* Overwrite */);

Easiest way to check if file exists within a subfolder

I am going getting all the folders within a folder as follows:
foreach (DirectoryInfo directory in root.GetDirectories())
I now want to check all the files in each of those folder individualally for an XML file.If the XML file exists I want to do something.
What would be the best way to go about this?
I know this is the basis:
if (File.Exists("*.xml"))
{
}
but that is not working?
Try this method if you want to actually do something with the XML file. If you are just checking to see if any xml file exists then I would go a different route:
foreach (DirectoryInfo directory in root.GetDirectories())
{
foreach(string file in Directory.GetFiles(directory.FullName, "*.xml"))
{
//if you get in here then do something with the file
//an "if" statement is not necessary.
}
}
http://msdn.microsoft.com/en-us/library/wz42302f.aspx
The Directory.GetFiles method:
if (Directory.GetFiles(#"C:\","*.xml").Length > 0) {
// Do something
}
As an alternative you could use Directory.GetFiles with your search pattern and action upon the found files...
var existing = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories);
//...
foreach(string found in existing) {
//TODO: Action upon the file etc..
}
foreach (DirectoryInfo directory in root.GetDirectories())
{
// What you have here would call a static method on the File class that has no knowledge
// at all of your directory object, if you want to use this then give it a fully qualified path
// and ignore the directory calls altogether
//if (File.Exists("*.xml"))
FileInfo[] xmlFiles = directory.GetFiles("*.xml");
foreach (var file in xmlFiles)
{
// do whatever
}
}

Copy Folders in C# using System.IO

I need to Copy folder C:\FromFolder to C:\ToFolder
Below is code that will CUT my FromFolder and then will create my ToFolder.
So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder
System.IO.Directory.Move(#"C:\FromFolder ", #"C:\ToFolder");
But i just want to Copy the files in FromFolder to ToFolder.
For some reason there is no System.IO.Directory.Copy???
How this is done using a batch file - Very easy
xcopy C:\FromFolder C:\ToFolder
Regards
Etienne
This link provides a nice example.
http://msdn.microsoft.com/en-us/library/cc148994.aspx
Here is a snippet
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
there is a file copy.
Recreate folder and copy all the files from original directory to the new one
example
static void Main(string[] args)
{
DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");
CopyDirectory(sourceDir, destinationDir);
}
static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
if (!destination.Exists)
{
destination.Create();
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName,
file.Name));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).
yes you are right.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
has provided copy function ..
or you can use another function
http://msdn.microsoft.com/en-us/library/ms127960.aspx
You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.
string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
fileName=Path.GetFileName(s);
destFile = Path.Combine(DestinationPath, fileName);
File.Copy(s, destFile);
}
I leave creating the destination directory to you :-)
You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.
I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.
A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist
class Utils
{
internal static void copy_dir(string source, string dest)
{
if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
Directory.CreateDirectory(dest);
foreach (string fn in Directory.GetFiles(source))
{
File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
}
foreach (string dir_fn in Directory.GetDirectories(source))
{
copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
}
}
}
This article provides an alogirthm to copy recursively some folder and all its content
From the article :
Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.
Good luck!
My version of DirectoryInfo.CopyTo using extension.
public static class DirectoryInfoEx {
public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (!target.Exists)
target.Create();
foreach (FileInfo f in source.GetFiles()) {
FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
f.CopyTo(newFile.FullName, true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
diSourceSubDir.CopyTo(nextTargetSubDir);
}
}
}
And use like that...
DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));

Categories

Resources