How to change a streamwriter encoding?

  • Thread starter Thread starter Diego F.
  • Start date Start date
D

Diego F.

Hi. I'm using that code:

If File.Exists(Ls_NombreFichero) = False Then
sw = File.CreateText(Ls_NombreFichero)
Else
sw = File.AppendText(Ls_NombreFichero)
End If

I need to change the encoding, as utf-8 is not the one I can use. How can I
change it? Encoding property is read only and I don't know how to use the
proper constructor.
 
Hi. I'm using that code:

If File.Exists(Ls_NombreFichero) = False Then
sw = File.CreateText(Ls_NombreFichero)
Else
sw = File.AppendText(Ls_NombreFichero)
End If

I need to change the encoding, as utf-8 is not the one I can use. How can I
change it? Encoding property is read only and I don't know how to use the
proper constructor.
--

Regards,

Diego F.

I'm a bit confused - the FileStream object, which is created by
CreateText and AppendText, does not have a Encoding property.

Thanks,

Seth Rowe
 
I'm a bit confused - the FileStream object, which is created by
CreateText and AppendText, does not have a Encoding property.

Thanks,

Seth Rowe

Sorry - I confused myself, I was looking at the Create method and not
the CreateText method.

Perhaps you could create your StreamWriter from the FileStream
returned by File.Create()? Then you could set the encoding in the
constructor like so:

/////////////////////
sw = New StreamWriter(File.Create(Ls_NombreFichero),
System.Text.Encoding.UTF32)
/////////////////////

As far as the AppendText, I think you will need to read the file
contents, delete the old file, and then use the above method to
rewrite the file with the new encoding. There may be a way to change
the encoding of an existing file, but I'm not sure what it is.

Thanks,

Seth Rowe
 
Back
Top