My idea is to make my life a littler easier by encapsulating the StreamReader and StreamWriter classes, the goal here is to have this class provide static methods that i can call to write and read from a file without having to instantiate objects of type StreamWriter/Reader and so on.
So far, I have the following code for my class:
Option Strict On
Imports System.IO
Imports System.IO.StreamReader
Imports System.IO.StreamWriter
Public Class ReadWrite
Enum WriteType
Append = 0
WriteLine = 1
Write = 2
End Enum
Enum ReadType
Readline = 0
Read = 1
End Enum
Shared Function Write (ByVal FilePath As String, ByVal _WriteType As WriteType, ByVal Content As String) As Boolean
Select Case _WriteType
Case WriteType.Append
Using _append As StreamWriter = New StreamWriter(FilePath,True)
_append.WriteLine (Content)
End Using
Case WriteType.Write
Using _write As StreamWriter = New StreamWriter(FilePath, False)
_write.Write (Content)
End Using
Case WriteType.WriteLine
Using _writeline As StreamWriter = New StreamWriter(FilePath, False)
_writeline.Writeline (Content)
End Using
End Select
Return false
End Function
Shared Function Read (ByVal FilePath As String, ByVal _ReadType As ReadType) As Boolean
Select Case _ReadType
Case ReadType.ReadLine
Case ReadType.Read
End Select
Return false
End Function
End Class
Question:
Is this a good method of accomplishing such task? What are some techniques i can use that will yield good results while maintaining code re-usability and simplicity; my goal is to make this flexible enough to use easily in other applications.
Thank you!
There is in general nothing wrong with writing little helper methods to make your life easier. But unfortunately you picked a Really Bad example.
What goes wrong here is that you open and close a file for every single little bit of data you read or write to the file. Opening a file is an expensive operation, on most common hardware that costs around 50 milliseconds. And it is horribly prone to random failure, by closing a file you give another process the chance to open the file. Which may well lock you out, your next read/write can easily fail with an “access denied” exception. Impossible to debug since it is so random and caused by another process you can’t see.
A simple workaround is to give the helper method an argument type of TextReader or TextWriter instead of string. Or by taking advantage of extension methods.