1 EXAMPLES ON FILESYSTEMS Reading From and Writing to Files

advertisement
EXAMPLES ON FILESYSTEMS
File Access Through StreamReader and StreamWriter Classes
The System.IO Namespace class allows you to read and write characters to and from files as streams, or
contiguous groups of data, using specific encoding to convert characters to and from bytes. It includes a pair of
classes, StreamReader and StreamWriter, which enable you to read or write a sequential stream of
characters to or from a file.
The StreamReader class is derived from an abstract class called TextReader, which reads characters from a
stream or file. The StreamWriter class is derived from an abstract class called TextWriter, which writes
characters to a stream or file.
Security Note When writing to files, an application may need to create a file if the file to which it is trying to
write does not exist. To do so, it needs permission for the directory in which the file is to be created. However, if
the file already exists, the application only needs Write permission to the file itself. Wherever possible, it is more
secure to create the file during deployment and only grant Write permission to that file, rather than to the entire
directory. It is also more secure to write data to user directories than to the root directory or the Program Files
directory.
Uses:
Imports System
Imports System.IO
Reading From and Writing to Files
The following example writes a line of text to a file.
Dim file As New System.IO.StreamWriter(Server.MapPath("testpermission\d69.html"))
file.WriteLine("Here is the first line.")
file.Close()
The following example reads the text from a file into one string variable and writes the text to the console.
Dim file As New System.IO.StreamReader(Server.MapPath("testpermission\d69.html"))
Dim words As String = file.ReadToEnd()
Lbloutput.Text = words
file.Close()
The following example adds text to an existing file.
Dim file As New System.IO.StreamWriter(Server.MapPath("testpermission\d69.html"), True)
file.WriteLine("Here is another line.")
file.Close()
The following example reads one line at a time from a file and prints each line to the console.
Dim file As New System.IO.StreamReader(Server.MapPath("testpermission\TestFile.txt"))
Dim oneLine As String
oneLine = file.ReadLine()
While (oneLine <> "")
Lbloutput.Text += “<BR>” & oneLine
oneLine = file.ReadLine()
End While
file.Close()
The following code example shows a simple way to read text lines from a text file with Try..Catch.
Try
' Create an instance of StreamReader to read from a file.
Dim sr As StreamReader = New StreamReader(Server.MapPath("testpermission\Test.txt"))
Dim line As String
' Read and display the lines from the file until the end of the file is reached.
1
Do
line = sr.ReadLine()
Lbloutput.Text += “<BR>” & oneLine
Loop Until line Is Nothing
sr.Close()
Catch E As Exception
' Let the user know what went wrong.
lbloutput.Text = "The file could not be read:<BR>"
Lbloutput.Text += E.Message)
End Try
The following code example reads an entire file and notifies you when the end of the file is detected.
Dim FILE_NAME As String = "MyFile.txt"
If Not File.Exists(FILE_NAME) Then
lbloutput.Text = FILE_NAME
Return
End If
Dim sr As StreamReader = File.OpenText(FILE_NAME)
Dim input As String
input = sr.ReadLine()
While Not input Is Nothing
lbloutput.Text += line
input = sr.ReadLine()
End While
Lbloutput += "The end of the stream has been reached."
sr.Close()
The following code example shows a simple way to write text to a text file.
' Create an instance of StreamWriter to write text to a file.
Dim sw As StreamWriter = New StreamWriter("TestFile.txt")
' Add some text to the file.
sw.Write("This is the ")
sw.WriteLine("header for the file.")
sw.WriteLine("-------------------")
' Arbitrary objects can also be written to the file.
sw.Write("The date is: ")
sw.WriteLine(DateTime.Now)
sw.Close()
The following code example creates a new text file and writes a string to it.
Private Const FILE_NAME As String = "MyFile.txt"
If File.Exists(FILE_NAME) Then
Lbloutput.Text = "{0} already exists.", FILE_NAME
Return
End If
Dim sr As StreamWriter = File.CreateText(FILE_NAME)
sr.WriteLine("This is my file.")
sr.WriteLine("I can write ints {0} or floats {1}, and so on.", 1, 4.2)
sr.Close()
The following example appends text to a file.
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
2
sw = File.CreateText(path)
sw.WriteLine("Hello")
sw.WriteLine("And")
sw.WriteLine("Welcome")
sw.Flush()
sw.Close()
End If
' This text is always added, making the file longer over time
' if it is not deleted.
sw = File.AppendText(path)
sw.WriteLine("This")
sw.WriteLine("is Extra")
sw.WriteLine("Text")
sw.Flush()
sw.Close()
' Open the file to read from.
Dim sr As StreamReader = File.OpenText(path)
Dim s As String
Do While sr.Peek() >= 0
s = sr.ReadLine()
lbloutput.Text = s
Loop
sr.Close()
READING AND WRITING BINARY DATA
The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings.
The following code example demonstrates writing data to and reading data from a new, empty file stream
(Test.data). After creating the data file in the current directory, the associated BinaryWriter and BinaryReader
are created, and the BinaryWriter is used to write the integers 0 through 10 to Test.data, which leaves the file
pointer at the end of the file. After setting the file pointer back to the origin, the BinaryReader reads out the
specified content.
Dim FILE_NAME As String = Server.MapPath("testpermission\Test.data")
' Create the new, empty data file.
If File.Exists(FILE_NAME) Then
Lbloutput.Text = "{0} already exists!", FILE_NAME
Return
End If
Dim fs As New FileStream(FILE_NAME, FileMode.CreateNew)
Dim w As New BinaryWriter(fs)
' Create the writer for data.
' Write data to Test.data.
Dim i As Integer
For i = 0 To 10
w.Write(CInt(i))
Next i
w.Close()
fs.Close()
' Create the reader for data.
fs = New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
Dim r As New BinaryReader(fs)
' Read data from Test.data.
3
For i = 0 To 10
Lbloutput.Text += r.ReadInt32().ToString
Next i
w.Close()
WORKING WITH DIRECTORIES AND SUBDIRECTORIES:
The following code example shows how to use the I/O classes to create a listing of a directory.
Dim dir As New DirectoryInfo(Server.MapPath("..\s05test\"))
Dim f As FileInfo
lbloutput.Text = "List of .aspx Files: <BR>"
For Each f In dir.GetFiles("*.aspx")
Dim name As String = f.FullName
Dim size As Long = f.Length
Dim creationTime As DateTime = f.CreationTime
lbloutput.Text += size & " " & creationTime & " " & name
Next f
In this example, the code lists all files in the directory having a .aspx extension, along with their file size, creation
time, and name.
The following code example shows how to list the subdirectories.
Dim DD As DirectoryInfo = New DirectoryInfo(Server.MapPath("..\s05test\"))
Dim SD As DirectoryInfo
lbldirinfo.Text = lbldirinfo.Text & "<BR><hr /><b>Subdirectories of s05</b><BR><BR>"
For Each SD In DD.GetDirectories()
lbldirinfo.Text &= SD.Name & "<BR>"
Next
Visit the following sites to read more on the file systems:
http://msdn.microsoft.com/library/default.asp?url=/library/enus/vbcn7/html/vaconaccessthroughstreamreaderstreamwriterclasses.asp
http://support.microsoft.com/kb/304427/EN-US/
http://msdn.microsoft.com/library/default.asp?url=/library/enus/vbcn7/html/vbconintroductiontofilesystemobjectmodel.asp
microsoft.public.dotnet.languages.vb
4
Download