Friday, 25 September 2015

Copy, Move and Delete Files and Folders in C#:


Below are the commonly used methods (using “System.IO” namespace):

For deleting:
 File:          File.Delete(“Path to the file”);
 Folder:     Directory.Delete(“Path to the folder”);

The above methods will delete the file \ folder permanently. User cannot restore them back.

For Copying:
File:          File. Copy(“source path” , “destination path”);
 Folder:     You will have to recursively traverse through the source directory and create directory and copy files.

For Moving:
File:          File.Move(“source path” , “destination path”);
 Folder:     Directory.Move(“ source path” , “destination path”);

The above methods wouldn’t display the error dialogs, in case of any error OR the progress dialog to show the progress.

"Microsoft.VisualBasic.FileIO"namespace provides a class “FileSystem” that shows all the dialog such as Error dialog, Progress dialog etc. and it’s very simple to use. 



For deleting:
 File:          FileSystem.DeleteFile(“Path to the file”, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

 Folder:     FileSystem.DeleteDirectory(“Path to the file”, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

Here  3rd Argument:  RecycleOption also provide 2 options:
  • Delete to Recycle Bin.
  • Delete permanently.


For Copying:
File:          FileSystem.CopyFile(“ source path” , “destination path”, UIOption.OnlyErrorDialogs);
Folder:     FileSystem.CopyDirectory(sourceFile, destFile, UIOption.OnlyErrorDialogs);

For Moving:
File:          FileSystem.MoveFile(sourcePath, targetPath, UIOption.OnlyErrorDialogs);
Folder:     FileSystem.MoveDirectory(sourcePath, targetPath, UIOption.OnlyErrorDialogs);


Argument UIOption passed above provide 2 options:
  • To show only error dialogs
  •  To show all dialogs.