When specifying the location of a file or directory, you can use an absolute path, a relative path, or a UNC share path . The following are acceptable paths to a file: [4]
Table 18.3 shows the methods to use for performing copying, moving, and deletion of files. Code examples are given later. Table 18.3. Methods to use for performing common file operations
The difference between using File and FileInfo to perform the operations is that File contains static methods which take in the file path, while FileInfo needs to be instantiated with the file path before you perform operations on it. FileInfo encapsulates a file, while File is more like a utility class. FileInfo may take a bit longer to execute at first because of the object instantiation. If you simply want to perform a one-time file operation, it is preferable to use the static methods of File . However, if you want to perform multiple operations on a file, you might want to use FileInfo so that, after the initial instantiation, you can call other methods of that object. 18.1.1 Copying a fileTo copy a file, use either the non-static FileInfo.CopyTo method: FileInfo f = new FileInfo("c:\expt\loveletter.txt"); f.CopyTo("c:\backup\loveletter.txt"); or the static method File.Copy : File.Copy("c:\expt\loveletter.txt", "c:\backup\loveletter.txt"); Both result in the file c:\expt\loveletter.txt being copied over to c:\backup\loveletter.txt . Note that a System.IO.IOException is thrown if the target file already exists. Both methods are overloaded to take in an additional boolean parameter to indicate that you want to overwrite the target file if it exists without throwing the exception. // overwrite target file even if it exists f.CopyTo("c:\backup\loveletter.txt", true ); File.Copy("c:\expt\loveletter.txt", "c:\backup\loveletter.txt", true ); A System.IO.FileNotFoundException is thrown if the source file cannot be found. 18.1.2 Moving a fileTo move a file, use either the non-static FileInfo.MoveTo method: FileInfo f = new FileInfo("c:\expt\loveletter.txt"); f.MoveTo("c:\backup\loveletter.txt"); or the static method File.Move : File.Move("c:\expt\loveletter.txt", "c:\backup\loveletter.txt"); Both result in the file c:\expt\loveletter.txt being moved (copied over and deleted) to c:\backup\loveletter.txt . 18.1.3 Deleting a fileTo delete a file, use either the non-static FileInfo.Delete method: FileInfo f = new FileInfo("c:\expt\loveletter.txt"); f.Delete(); or the static method File.Delete : File.Delete ("c:\expt\loveletter.txt"); Both result in the file c:\expt\loveletter.txt being deleted. |