Writing to an XML File
Using the classes and methods of the XML Document Object Model, we can easily construct an…
The System.IO.FileInfo class is quite similar to the System.IO.File class in that, they are used for the same purpose of manipulating a file. The difference is that FileInfo does not have static methods so you need to create an instance of it first. The created FileInfoobject represents a file in the disk.
FileInfo file = new FileInfo(@"C:\Files\sample.txt");
The constructor accepts the file path of the file that the object will represent. Because we indicated the path in our constructor, calling the methods such as Create, Delete, Move, and Copy is simpler because we don’t have to repeat indicating the file path or source path in the method calls. For example, the following shows the difference of the System.IO.File and System.IO.FileInfo classes when calling the Create method.
FileInfo file = new FileInfo(@"C:\Files\sample.txt"); file.Create();
And the following shows the difference of moving and copying files.
File.Copy(@"C:\Source\sample.txt", @"C:\Dest\sample.txt"); File.Move(@"C:\Source\sample.txt", @"C:\Dest\sample.txt");
Note that we used CopyTo and MoveTo for the FileInfo object instead of Copy and Move and we only indicated the destination since the source path was indicated when we created the object.
The following are some of the basic methods of the FileInfo class.
|Create||Creates a new file.|
|Delete||Deletes the file associated with the FileInfo object.|
|CopyTo||Copies the file to the indicated destination path. An overload accepts a second boolean argument indicating whether to overwrite any existing file in the destination path.|
|MoveTo||Moves the file to the indicated destination path.|
|Open||Creats a FileStream that can be used to read or write to the file.|
Figure 1 – FileInfo Methods
The following are some of the properties of the FileInfo class.
|CreationTime||Get’s the time the file was created. Returns the result as a DateTime object.|
|Directory||Returns the DirectoryInfo which contains the information of the directory where the file is located.|
|Exists||Tells whether the specified path in the constructor exists in the file system.|
|Extention||Returns the extension name of the file as string. (“.txt”)|
|IsReadOnly||Tells whether the file is read-only.|
|LastAccessTime||Gets the last time the file was accessed. Returns the result as a DateTime object.|
|LastWriteTime||Gets the last time the file’s content was modified. Returns the result as a DateTime object.|
|Length||Gets the size in bytes of the current file.|
|Name||Gets the file name of the file. (“sample.txt”)|
|FullName||Gets the full name of the file. (“C:\Files\sample.txt”)|
Figure 2 – FileInfo Properties
More properties and methods are present in the FileInfo object and we will discuss them as we progress further to the next lessons.