Introduction
I have been working with the .NET framework for several weeks now and I really enjoy the API. But sometimes I miss some features I need right now, even if I expect the framework to grow and get new classes and capabilities in the forthcoming versions (like Java did).
This article doesn't try to teach something but just gives a solution to anyone who needs it. I tried to keep it simple with few lines of code.
The FileSystem
class
This class includes high level functions missing in the standard System.IO
namespace. The class provided here only includes a directory to directory copy function for the moment, and the purpose of this article is to fix this .NET missing feature that many VB developers (for example) are used to.
The function takes two absolute paths (source directory and destination directory) as parameters and returns a boolean
equal to true
when the copy succeeds. Please note that this function automatically overwrites a destination file with the same name. Of course all subdirectories are also copied recursively.
using System;
using System.IO;
namespace Utility.IO{
public class FileSystem{
public static void copyDirectory(string Src,string Dst){
String[] Files;
if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar)
Dst+=Path.DirectorySeparatorChar;
if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
Files=Directory.GetFileSystemEntries(Src);
foreach(string Element in Files){
if(Directory.Exists(Element))
copyDirectory(Element,Dst+Path.GetFileName(Element));
else
File.Copy(Element,Dst+Path.GetFileName(Element),true);
}
}
}
}
An usage example
Here is an example of how to use the FileSystem
class.
try{
copyDirectory(@"c:\MySrcDirectory",@"c:\MyDstDirectory");
}
catch(Exception Ex){
Console.Error.WriteLine(Ex.Message);
}
Conclusion
This article is just a tip targeted to beginners or newcomers who noticed this missing feature in the .NET framework. It is provided as a possible solution, but I encourage anyone to write his own function.
Happy Coding !!!