File Information: Operations on Files |
|
|
Deleting a File |
If you have an existing file you don't need anymore, you can delete it. This operation can be performed by calling the FileInfo.Delete() method. Its syntax is: public void Delete(); Here is an example: private void btnDelete_Click(object sender, System.EventArgs e) { FileInfo fleMembers = new FileInfo("First.txt"); fleMembers.Delete(); } |
Copying a File |
You can make a copy of a file from one directory to another. To do this, you can call the FileInfo.CopyTo() method that is overloaded with two versions. The first version has the following syntax: public FileInfo CopyTo(string destFileName); When calling this method, specify the path or directory that will be the destination of the copied file. Here is an example: private void btnCopy_Click(object sender, System.EventArgs e) { FileInfo fleMembers = new FileInfo("Reality.txt"); String strMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.Personal); fleMembers.CopyTo(String.Concat(strMyDocuments, "\\Federal.txt")); } In this example, a file named Reality.txt in the directory of the project would be retrieved and its content would be applied to a new file named Federal.txt created in the My Documents folder of the local computer. When calling the first version of the FileInfo.CopyTo() method, if the file exists already, the operation would not continue and you would simply receive a message box. If you insist, you can overwrite the target file. To do this, you can use the second version of this method. Its syntax is: public FileInfo CopyTo(string destFileName, bool overwrite); The first argument is the same as that of the first version of the method. The second argument specifies what action to take if the file exists already in the target directory. If you want to overwrite it, pass the argument as true; otherwise, pass it as false. |
Moving a File |
If you copy a file from one directory to another, you would have two copies of the same file or the same contents in two files. Instead of copying, if you want, you can simply move the file from one directory to another. This operation can be performed by calling the FileInfo.MoveTo() method. Its syntax is: public void MoveTo(string destFileName); The argument to this method is the same as that of the CopyTo() method. After executing this method, the FileInfo object would be moved to the destFileName path. Here is an example: private void btnMove_Click(object sender, System.EventArgs e) { FileInfo fleMembers = new FileInfo("pop.txt"); String strMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.Personal); fleMembers.CopyTo(String.Concat(strMyDocuments, "\\pop.txt")); } |
|
||
Previous | Copyright © 2005-2016, FunctionX | Next |
|