Files and Directories in VB.NET

In this article I will explain you about Files and Directories in VB.NET
  • 3314

Under Windows, the file system is divided into files and directories (or folders). Files are the actual files of data, while directories are repositories for logical placement of files on your system. Under the System.IO namespace, the common language runtime (CLR) has the classes File, FileInfo, Directory, and DirectoryInfo to deal with files and directories.

File and FileInfo Classes

The basic functionality of both the File class and FileInfo class is the same. It differs only in that the File class provides static methods to deal with files whereas the FileInfo class provides instance methods to deal with files. The choice belongs to the programmer. Table 1.1 below shows a side-byside comparison of the two file manipulation class methods:

File Class (Static Methods) FileInfo Class Use Copy CopyTo Copy a file to a destination path. Create Create Create a file. Delete Delete Delete the file. Exists Exists (property) Check whether the file exists. Note: The File class implements a method Exists while the FileInfo class implements Exists as a property. Move MoveTo Move the file to a destination path. Open Open Open a FileStream to the file.

Table 1.1: File and FileInfo class members


The FileInfo class has a single constructor that takes a single parameter of a string containing the path to the file. The path to the file can be a fully qualified path or a relative one. The file need not exist when you make a FileInfo object, so making FileInfo objects is as simple as the code shown in below example.

Example of Constructing a FileInfo Object

      Dim f1 As New FileInfo("c:\temp\readme.txt") //Fully qualified path
      Dim f2 As New FileInfo("\db\myData.xml")//Relational path
      Dim f3 As New FileInfo(@"\db\myData.xml")//Use of a verbatim string literal

You can use the at symbol (@) to define a verbatim string that does not need to have an escape sequence in it, making it easier to read.

Some of the important properties of the FileInfo class are Attributes, CreationTime, DirectoryName, Exists, FullName, Length, and Name.

Since the File class consists of static methods, you can perform many of the necessary file functions without creating an instance of the file, as shown in next example.

Example of Using Static File Methods

        File.Copy(@"c:\temp\readme.txt",@"d:\temp\readme.txt")//Copy a file
        File.Create(@"C:\temp\newdoc.txt")//Create a file
        File.Delete(@"C:\temp\readme.txt")//Delete a file
 File.Move(@"d:\temp\readme.txt",@"c:\temp\readme.txt")//Move a file


Hope this article would have helped you in understanding Files and Directories in VB.NET


More Articles

© 2020 DotNetHeaven. All rights reserved.