Hello, I am working on a sub that essentially needs to open a text file, and replace all instances of a certain character with a unicode character.
I'm trying to do this by reading the original text file byte by byte, converting it to a character, and then either adding that character to a memory stream or writing the unicode character to the memory stream. Then I'm saving the memory stream to the original file.
Everything is working correctly except the last few lines of the file are always missing. I have tried setting my StreamWriter to a FileStream instead of a MemoryStream and it saves the whole file that way, so I believe it is an issue with the MemoryStream. From what I've read its capacity should be expandable by default and I don't have any experience with them so idk what else would cause this.
I am using VS2003 and this method is being called by an ASP page if that has anything to do with it.
The text file is 40-100KB.
I'm trying to do this by reading the original text file byte by byte, converting it to a character, and then either adding that character to a memory stream or writing the unicode character to the memory stream. Then I'm saving the memory stream to the original file.
Everything is working correctly except the last few lines of the file are always missing. I have tried setting my StreamWriter to a FileStream instead of a MemoryStream and it saves the whole file that way, so I believe it is an issue with the MemoryStream. From what I've read its capacity should be expandable by default and I don't have any experience with them so idk what else would cause this.
I am using VS2003 and this method is being called by an ASP page if that has anything to do with it.
The text file is 40-100KB.
VB.NET:
Sub newBar(ByVal path As String)
Dim fs As FileStream
Dim sr As StreamReader
Dim ms As MemoryStream
Dim sw As StreamWriter
Dim strLine As String
Dim strChar As Char
Dim charBytes() As Byte
Try
fs = New FileStream(path, FileMode.Open) 'fs is a filestream to the
'existing report
ms = New MemoryStream 'ms is a chunk of memory to save a copy of
'the file before we over write the original
sw = New StreamWriter(ms, System.Text.Encoding.Unicode) 'sw is used to
'write to ms in
'unicode
While fs.Position < fs.Length
strChar = (ChrW(fs.ReadByte)) 'read each char
If strChar = "*" Then 'if it is the escape char
sw.Write(ChrW(&H25A0)) 'write a black square
Else
sw.Write(strChar) 'otherwise write the original char
End If
End While
sw.Flush()
fs.Close() 'close the original report file
fs = New FileStream(path, FileMode.Create)'re-open file in filemode.create
'(overwrite existing)
ms.WriteTo(fs) 'over write existing file with new file.
fs.Flush() 'make sure all data is saved before closing file
Catch
Finally
'clean up
sw.Close() 'close stream writer
ms.Close() 'close memory stream
fs.Close() 'close file
End Try
End Sub
Last edited: