Kamran Ahmed

Files Handling in .NET



Files in VB .NET

Working with Files

File handling in Visual Basic is based on System.IO namespace with a class library that supports string, character and file manipulation. These classes contain properties, methods and events for creating, copying, moving, and deleting files. Since both strings and numeric data types are supported, they also allow us to incorporate data types in files. The most commonly used classes are FileStream, BinaryReader, BinaryWriter, StreamReader and StreamWriter.
FileStream Class
This class provides access to standard input and output files. We use the members of FileAccess, FileMode and FileShare Enumerations with the constructors of this class to create or open a file. After a file is opened it's FileStream object can be passed to the Binary Reader, BinaryWriter, Streamreader and StreamWriter classes to work with the data in the file. We can also use the FileStreamSeek method to move to various locations in a file which allows to break a file into records each of the same length.
StreamReader and StreamWriter Class
The StreamReader and StreamWriter classes enables us to read or write a sequential stream of characters to or from a file.
BinaryReader and BinaryWriter Class
The BinaryReader and BinaryWriter classes enable us to read and write binary data, raw 0's and 1's, the form in which data is stored on the computer.
The following examples puts some code to work with textual data using FileStream and StreamReader and StreamWriter classes.
Code to create a File
Imports System.IO
'NameSpace required to be imported to work with files
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim fs as New FileStream("file.doc", FileMode.Create, FileAccess.Write)
'declaring a FileStream and creating a word document file named file with
'access mode of writing
Dim s as new StreamWriter(fs)
'creating a new StreamWriter and passing the filestream object fs as argument
s.BaseStream.Seek(0,SeekOrigin.End)
'the seek method is used to move the cursor to next position to avoid text to be
'overwritten
s.WriteLine("This is an example of using file handling concepts in VB .NET.")
s.WriteLine("This concept is interesting.")
'writing text to the newly created file
s.Close()
'closing the file
End Sub
End Class
The default location where the files we create are saved is the bin directory of the Windows Application with which we are working.
Code to create a file and read from it
Drag a Button and a RichTextBox control onto the form. Paste the following code which is shown below.
Imports System.IO
'NameSpace required to be imported to work with files
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal....., Byval.....)Handles Button1.Click
Dim fs as New FileStream("file.doc", FileMode.Create, FileAccess.Write)
'declaring a FileStream and creating a document file named file with
'access mode of writing
Dim s as new StreamWriter(fs)
'creating a new StreamWriter and passing the filestream object fs as argument
s.WriteLine("This is an example of using file handling concepts in VB .NET.")
s.WriteLine("This concept is interesting.")
'writing text to the newly created file
s.Close()
'closing the file

fs=New FileStream("file.doc",FileMode.Open,FileAccess.Read)
'declaring a FileStream to open the file named file.doc with access mode of reading
Dim d as new StreamReader(fs)
'creating a new StreamReader and passing the filestream object fs as argument
d.BaseStream.Seek(0,SeekOrigin.Begin)
'Seek method is used to move the cursor to different positions in a file, in this code, to
'the beginning
while d.peek()>-1
'peek method of StreamReader object tells how much more data is left in the file
RichTextbox1.Text &= d.readLine()
'displaying text from doc file in the RichTextBox
End while
d.close()
End Sub
Working with Directories
We will work with the File and Directory classes in this section. We will create a directory and copy a file into the newly created directory.
File Class
The File class in VB .NET allows us to work with files, allowing to copy, delete and create files.
Directory Class
The Directory class in VB .NET allows us to create and work with Folders/Directories. With this class we can create, edit and delete folders and also maintain drives on the machine.
Code to work with File and Directory Class
The following code will create a directory and copy a file into that new directory. To create a new directory we should use the Directory class's CreateDirectory method. Drag two Button's (Button1, Button2), a TextBox and a OpenFileDialog control from the toolbar onto the Form. We will use the TextBox to specify a location to create the Directory when Button1 is clicked and the OpenFileDialog control to open a file and copy it into the newly created Directory when Button2 is clicked. The namespace to be imported is System.IO. The code for that looks like this:
Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form

 'Windows Form Designer Generated Code

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click

Try
Directory.CreateDirectory(TextBox1.Text)
 'Creating a directory by specifying a path in the TextBox, of the form c:\examples
'Instead of using a TextBox you can directly type the location of the directory like this
'Directory.CreateDirectory("c:\examples")
Catch
End Try
MsgBox("Done")
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button2.Click
Try
If OpenFileDialog1.ShowDialog <> DialogResult.Cancel Then
File.Copy(OpenFileDialog1.FileName, TextBox1.Text & "\" & _
OpenFileDialog1.FileName.Substring(OpenFileDialog1.FileName.LastIndexOf("\")))
'The above line of code uses OpenFileDialog control to open a dialog box where you
'can select a file to copy into the newly created directory
End If
Catch
End Try
MsgBox("File Copied Successfully")
End Sub
End Class
That's all it takes to create a directory and copy a file into the newly created directory in VB.NET.

No comments:

Post a Comment