Introduction
During the process of moving some command scripts to a more robust solution that involved C# Script, I was in the need to replace several XCOPY calls with their equivalents in C#.
What I wanted to avoid is to simply start a CMD.EXE process and call the XCOPY command.
Instead I looked for a class/function in .NET/C# that can serve as a replacement. Although I found some solutions, none of them worked the way I wanted them.
Using the Code
So I decided to develop my own small solution that is no rocket science code but fulfills my requirements.
It has fewer features than XCOPY and is intended for copying folders (the original XCOPY works for both files and folders). In addition it is being designed to be used in a console environment (i.e., the operations are synchronous and blocking).
An example call looks like:
var options =
new ZetaFolderXCopyOptions
{
FilesPattern = "*.*",
RecurseFolders = true,
CopyEmptyFolders = true,
CopyHiddenAndSystemFiles = true,
OverwriteExistingFiles = true,
CopyOnlyIfSourceIsNewer = false,
FoldersPattern = "*"
}
.AddExcludeSubStrings(
"\\.svn\\",
"\\_svn\\",
"\\_Temporary\\" );
var xc = new ZetaFolderXCopy();
xc.Copy(
sourceFolderPath,
destinationFolderPath,
options );
The full code consists of a single .CS file and can be downloaded from the top of this article.
Simply drop it into your solution/script and use it.
Epilog
This article introduced a small class to do basic operations that XCOPY and ROBOCOPY do from within your own C# code.
As always, I would love to get your feedback, suggestions and enhancements. Feel free to drop me a note below in the discussions section of the article.
History
- 2018-05-27 — Newest snippet is at this Pastebin
- 2009-09-25 — First release