Showing posts with label VB.Net - File Handling. Show all posts
Showing posts with label VB.Net - File Handling. Show all posts

Saturday, 14 September 2013

VB.Net - Manipulating the Windows File System

VB.Net allows you to work with the directories and files using various directory and file related classes like, the DirectoryInfo class and the FileInfo class.

The DirectoryInfo Class

The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited.
Following are some commonly used properties of the DirectoryInfo class:
S.NProperty Name & Description
1Attributes
Gets the attributes for the current file or directory.
2CreationTime
Gets the creation time of the current file or directory.
3Exists
Gets a Boolean value indicating whether the directory exists.
4Extension
Gets the string representing the file extension.
5FullName
Gets the full path of the directory or file.
6LastAccessTime
Gets the time the current file or directory was last accessed.
7Name
Gets the name of this DirectoryInfo instance.
Following are some commonly used methods of the DirectoryInfo class:
S.NMethod Name & Purpose
1Public Sub Create
Creates a directory.
2Public Function CreateSubdirectory ( path As String ) As DirectoryInfo 
Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
3Public Overrides Sub Delete
Deletes this DirectoryInfo if it is empty.
4Public Function GetDirectories As DirectoryInfo()
Returns the subdirectories of the current directory.
5Public Function GetFiles As FileInfo()
Returns a file list from the current directory.
For complete list of properties and methods please visit Microsoft's documentation.

The FileInfo Class

The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited.
Following are some commonly used properties of the FileInfo class:
S.NProperty Name & Description
1Attributes
Gets the attributes for the current file.
2CreationTime
Gets the creation time of the current file.
3Directory
Gets an instance of the directory which the file belongs to.
4Exists
Gets a Boolean value indicating whether the file exists.
5Extension
Gets the string representing the file extension.
6FullName
Gets the full path of the file.
7LastAccessTime
Gets the time the current file was last accessed.
8LastWriteTime
Gets the time of the last written activity of the file.
9Length
Gets the size, in bytes, of the current file.
10Name
Gets the name of the file.
Following are some commonly used methods of the FileInfo class:
S.NMethod Name & Purpose
1Public Function AppendText As StreamWriter
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
2Public Function Create As FileStream
Creates a file.
3Public Overrides Sub Delete
Deletes a file permanently.
4Public Sub MoveTo ( destFileName As String ) 
Moves a specified file to a new location, providing the option to specify a new file name.
5Public Function Open ( mode As FileMode ) As FileStream 
Opens a file in the specified mode.
6Public Function Open ( mode As FileMode, access As FileAccess ) As FileStream 
Opens a file in the specified mode with read, write, or read/write access.
7Public Function Open ( mode As FileMode, access As FileAccess, share As FileShare ) As FileStream 
Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.
8Public Function OpenRead As FileStream
Creates a read-only FileStream
9Public Function OpenWrite As FileStream
Creates a write-only FileStream.
For complete list of properties and methods, please visit Microsoft's documentation

Example

The following example demonstrates the use of the above mentioned classes:
Imports System.IO
Module fileProg
   Sub Main()
      'creating a DirectoryInfo object
      Dim mydir As DirectoryInfo = New DirectoryInfo("c:\Windows")
      ' getting the files in the directory, their names and size
      Dim f As FileInfo() = mydir.GetFiles()
      Dim file As FileInfo
      For Each file In f
          Console.WriteLine("File Name: {0} Size: {1}  ", file.Name, file.Length)
      Next file
      Console.ReadKey()
   End Sub
End Module
When you compile and run the program, it displays the names of files and their size in the Windows directory.

VB.Net - Reading from and Writing into Binary Files

The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.

The BinaryReader Class

The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryReader class.
S.NMethod Name & Purpose
1Public Overridable Sub Close
It closes the BinaryReader object and the underlying stream.
2Public Overridable Function Read As Integer
Reads the characters from the underlying stream and advances the current position of the stream.
3Public Overridable Function ReadBoolean As Boolean
Reads a Boolean value from the current stream and advances the current position of the stream by one byte.
4Public Overridable Function ReadByte As Byte
Reads the next byte from the current stream and advances the current position of the stream by one byte.
5Public Overridable Function ReadBytes ( count As Integer ) As Byte() 
Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes.
6Public Overridable Function ReadChar As Char
Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.
7Public Overridable Function ReadChars ( count As Integer ) As Char() 
Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.
8Public Overridable Function ReadDouble As Double
Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
9Public Overridable Function ReadInt32 As Integer
Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
10Public Overridable Function ReadString As String 
Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.

The BinaryWriter Class

The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryWriter class.
S.NFunction Name & Description
1Public Overridable Sub Close
It closes the BinaryWriter object and the underlying stream.
2Public Overridable Sub Flush
Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
3Public Overridable Function Seek ( offset As Integer, origin As SeekOrigin ) As Long 
Sets the position within the current stream.
4Public Overridable Sub Write ( value As Boolean ) 
Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true.
5Public Overridable Sub Write ( value As Byte ) 
Writes an unsigned byte to the current stream and advances the stream position by one byte.
6Public Overridable Sub Write ( buffer As Byte() ) 
Writes a byte array to the underlying stream.
7Public Overridable Sub Write ( ch As Char ) 
Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
8Public Overridable Sub Write ( chars As Char() ) 
Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
9Public Overridable Sub Write ( value As Double ) 
Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.
10Public Overridable Sub Write ( value As Integer ) 
Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.
11Public Overridable Sub Write ( value As String ) 
Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.
For complete list of methods, please visit Microsoft's documentation.

Example

The following example demonstrates reading and writing binary data:
Imports System.IO
Module fileProg
   Sub Main()
      Dim bw As BinaryWriter
      Dim br As BinaryReader
      Dim i As Integer = 25
      Dim d As Double = 3.14157
      Dim b As Boolean = True
      Dim s As String = "I am happy"
      'create the file
      Try
          bw = New BinaryWriter(New FileStream("mydata", FileMode.Create))
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot create file.")
          Return
      End Try
      'writing into the file
      Try
          bw.Write(i)
          bw.Write(d)
          bw.Write(b)
          bw.Write(s)
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot write to file.")
          Return
      End Try
      bw.Close()
      'reading from the file
      Try
          br = New BinaryReader(New FileStream("mydata", FileMode.Open))
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot open file.")
          Return
      End Try
      Try
           i = br.ReadInt32()
          Console.WriteLine("Integer data: {0}", i)
          d = br.ReadDouble()
          Console.WriteLine("Double data: {0}", d)
          b = br.ReadBoolean()
          Console.WriteLine("Boolean data: {0}", b)
          s = br.ReadString()
          Console.WriteLine("String data: {0}", s)
      Catch e As IOException
          Console.WriteLine(e.Message + "\n Cannot read from file.")
          Return
      End Try
      br.Close()
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Integer data: 25
Double data: 3.14157
Boolean data: True
String data: I am happy

VB.Net - Reading from and Writing to Text Files

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.

The StreamReader Class

The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly usedmethods of the StreamReader class:
S.NMethod Name & Purpose
1Public Overrides Sub Close
It closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
2Public Overrides Function Peek As Integer
Returns the next available character but does not consume it.
3Public Overrides Function Read As Integer
Reads the next character from the input stream and advances the character position by one character.

Example:

The following example demonstrates reading a text file named Jamaica.txt. The file reads:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
Imports System.IO
Module fileProg
   Sub Main()
      Try
          ' Create an instance of StreamReader to read from a file. 
          ' The using statement also closes the StreamReader. 
          Using sr As StreamReader = New StreamReader("e:/jamaica.txt")
              Dim line As String
              ' Read and display lines from the file until the end of  
              ' the file is reached. 
              line = sr.ReadLine()
              While (line <> Nothing)
                  Console.WriteLine(line)
                  line = sr.ReadLine()
              End While
          End Using
      Catch e As Exception
          ' Let the user know what went wrong.
          Console.WriteLine("The file could not be read:")
          Console.WriteLine(e.Message)
      End Try
      Console.ReadKey()
   End Sub
End Module
Guess what it displays when you compile and run the program!

The StreamWriter Class

The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character.
The following table shows some of the most commonly used methods of this class:
S.NMethod Name & Purpose
1Public Overrides Sub Close
Closes the current StreamWriter object and the underlying stream.
2Public Overrides Sub Flush
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
3Public Overridable Sub Write ( value As Boolean ) 
Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)
4Public Overrides Sub Write ( value As Char ) 
Writes a character to the stream.
5Public Overridable Sub Write ( value As Decimal ) 
Writes the text representation of a decimal value to the text string or stream.
6Public Overridable Sub Write ( value As Double ) 
Writes the text representation of an 8-byte floating-point value to the text string or stream.
7Public Overridable Sub Write ( value As Integer ) 
Writes the text representation of a 4-byte signed integer to the text string or stream.
8Public Overrides Sub Write ( value As String ) 
Writes a string to the stream.
9Public Overridable Sub WriteLine
Writes a line terminator to the text string or stream.
The above list is not exhaustive. For complete list of methods please visit Microsoft's documentation

Example:

The following example demonstrates writing text data into a file using the StreamWriter class:
Imports System.IO
Module fileProg
   Sub Main()
      Dim names As String() = New String() {"Zara Ali", _
         "Nuha Ali", "Amir Sohel", "M Amlan"}
      Dim s As String
      Using sw As StreamWriter = New StreamWriter("names.txt")
          For Each s In names
              sw.WriteLine(s)
          Next s
      End Using
      ' Read and show each line from the file. 
      Dim line As String
      Using sr As StreamReader = New StreamReader("names.txt")
          line = sr.ReadLine()
          While (line <> Nothing)
              Console.WriteLine(line)
              line = sr.ReadLine()
          End While
      End Using
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Zara Ali
Nuha Ali
Amir Sohel
M Amlan