WriteAllText

J

Jim

I'm parsing a file and writing a text file with cr/lf's on the end of
line. It works fine EXCEPT I get a hex FF FE as the first two
characters of the file.

1)How do I get rid of them
2)How did they get there
3)What did I do wrong?

Jim

Here's the code:
===============================
dim counter as string = ""

Using MyReader As New
Microsoft.VisualBasic.FileIO.TextFieldParser(openFileDialog1.FileName)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters("~")
counter = "0000*"
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String = ""
For Each currentField In currentRow
If VB.Left(currentField, 2) = "ST" Then
counter = VB.Right(currentField, 4) & "*"
End If
If VB.Left(currentField, 2) = "SE" Then
counter = "0000*"
End If
currentField = counter & currentField & vbCrLf
My.Computer.FileSystem.WriteAllText("C:/testfile.txt",
currentField, True)
Next
Catch ex As VB.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using
 
T

Tom Shelton

I'm parsing a file and writing a text file with cr/lf's on the end of
line. It works fine EXCEPT I get a hex FF FE as the first two
characters of the file.

FFFE... That's the Unicode Byte Order Marker (BOM). Reading the
docs, says that if you don't specify the encoding, then UTF-8 is used
(hence, you get the BOM at the begining of the file). So, it must be
calling System.IO.File.WriteAllText underneath, and explicitly passing
System.Text.Encoding.UTF8. File.WriteAllText uses UTF8 by default -
but, if you don't pass the encoding, then it doesn't insert the BOM.

I couldn't help it - I just looked at this in Reflector, and sure
enough, it explicitly passes UTF8 to the File.WriteAllText method.
That explains the BOM.

Just add System.Text.Encoding.ASCII to your call and it should
disappear.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top