Updated: July 2008
The following examples show how to copy, move, and delete files and folders in a synchronous manner by using the System.IO.File, System.IO.Directory, System.IO.FileInfo, and System.IO.DirectoryInfo classes from the System.IO namespace. These examples do not provide a progress bar or any other user interface. If you want to provide a standard progress dialog box, see How to: Provide a Progress Dialog Box for File Operations (C# Programming Guide).
Use System.IO.FileSystemWatcher to provide events that will enable you to calculate the progress when operating on multiple files. Another approach is to use platform invoke to call the relevant file-related methods in the Windows Shell. For information about how to perform these file operations asynchronously, see Asynchronous File I/O.
The following example shows how to copy files and directories.
// Simple synchronous file copy operations with no user interface. // To run this sample, first create the following directories and files: // C:\Users\Public\TestFolder // C:\Users\Public\TestFolder\test.txt // C:\Users\Public\TestFolder\SubDir\test.txt public class SimpleFileCopy { static void Main() { string fileName = "test.txt"; string sourcePath = @"C:\Users\Public\TestFolder"; string targetPath = @"C:\Users\Public\TestFolder\SubDir"; // Use Path class to manipulate file and directory paths. string sourceFile = System.IO.Path.Combine(sourcePath, fileName); string destFile = System.IO.Path.Combine(targetPath, fileName); // To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } // To copy a file to another location and // overwrite the destination file if it already exists. System.IO.File.Copy(sourceFile, destFile, true); // 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); } } else { Console.WriteLine("Source path does not exist!"); } // Keep console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }
The following example shows how to move files and directories.
// Simple synchronous file move operations with no user interface. public class SimpleFileMove { static void Main() { string sourceFile = @"C:\Users\Public\public\test.txt"; string destinationFile = @"C:\Users\Public\private\test.txt"; // To move a file or folder to a new location: System.IO.File.Move(sourceFile, destinationFile); // To move an entire directory. To programmatically modify or combine // path strings, use the System.IO.Path class. System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private"); } }
The following example shows how to delete files and directories.
// Simple synchronous file deletion operations with no user interface. // To run this sample, create the following files on your drive: // C:\Users\Public\DeleteTest\test1.txt // C:\Users\Public\DeleteTest\test2.txt // C:\Users\Public\DeleteTest\SubDir\test2.txt public class SimpleFileDelete { static void Main() { // Delete a file by using File class static method... if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt")) { // Use a try block to catch IOExceptions, to // handle the case of the file already being // opened by another process. try { System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); return; } } // ...or by using FileInfo instance method. System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt"); try { fi.Delete(); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } // Delete a directory. Must be writable or empty. try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } // Delete a directory and all subdirectories with Directory static method... if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest")) { try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } // ...or with DirectoryInfo instance method. System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public"); // Delete this dir and all subdirs. try { di.Delete(true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } }
Tasks
Concepts
Reference
Other Resources
|
Date |
History |
Reason |
|---|---|---|
|
July 2008 |
Added topic. |
Content bug fix. |
bool a=true;
bool b=false;
examples :
if(a && b) -> Will execute "else", because it's not true : true && false -> false
if(a && !b) -> Will execute "then" because it's true : true && !false -> true && true -> true
if (System.IO.Directory.Exists(targetPath)) means : If directory "targetPath" does exists, then ...
if (!System.IO.Directory.Exists(targetPath)) means If directory "targetPath" does NOT exists, then...
Just look to c# operators topic before supposing that "!" is useless! If it would have been, it would not have been used, don't you think?
The error at runtime might just be a logic error in "then" or either "else" statement according to the thing that have been verified by the if?
I believe the following line contains a typo; where the '!' should not be included. With this ! I recieve an error at runtime. When I remove the !, the code seems to work as expected. I did a little searching and was unable to determine that an ! in C# does anything useful. If you have trouble, I suggest removing the excalmation point.
if (!System.IO.Directory.Exists(targetPath))
[tfl - 21 05 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at
http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&