Writing a string to a file - weird characters

G

Guest

Hi guys,
I'm wondering if you can help me.

For some reason when I use a StreamWriter to write a string to a file there
are weird characters appearing at the start of the file.

The only reason I can notice these characters is because I'm trying to read
the file in Java, and the first few characters aren't meant to be there.

My code (however trivial) looks like this:

Dim fileWriter As StreamWriter
fileWriter =
My.Computer.FileSystem.OpenTextFileWriter(SaveFileDialog.FileName, False)
fileWriter.Write(strContents)
fileWriter.Close()

Where strContents is a String I have already populated.

If I use the following code:

Dim fso As Object, text As Object
fso = CreateObject("scripting.filesystemobject")
text = fso.CreateTextFile(SaveFileDialog.FileName & "1")
text.WriteLine(strContents)

The characters don't appear. So, how am I misusing my StreamWriter? How can
I get it to stop writing those characters?

Thanks in advance,

Joe
 
J

Jon Skeet [C# MVP]

Riga said:
I'm wondering if you can help me.

For some reason when I use a StreamWriter to write a string to a file there
are weird characters appearing at the start of the file.

It's the byte order mark. If you don't want it, you could tell the
StreamWriter to use an Encoding which doesn't have it - either use a
different encoding such as ASCII, or create a new instance of
UTF8Encoding with the appropriate constructor (see the docs).
The only reason I can notice these characters is because I'm trying to read
the file in Java, and the first few characters aren't meant to be there.

Make sure you read the file in Java as UTF-8, using an
InputStreamReader with the appropriate encoding. I'm not *sure* whether
InputStreamReader removes BOMs or not - try it.
 

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