0

I have a directory in my web proyect with this file:

home.text

and inside the home.txt file I have this text:

ESPAÑA_BOLSA.xlsx

So I have this code in vb.net to extract the text from the .txt file:

Public Shared Function GetTextFromTXT() As String       
        Dim FilePath As String = HttpContext.Current.Server.MapPath("~/excel/home.txt")
        ' Creates instance of StreamReader class
        Dim sr As StreamReader = New StreamReader(FilePath)
        ' Finally, loads file to string
        Dim FileContent As String = sr.ReadToEnd().ToString
  Return FileContent
End Function

but with this code I get this result in Filecontent:

ESPA�A_BOLSA.xlsx

So I use this line to try to decode the text, but is not work:

  FileContent = WebUtility.HtmlDecode(FileContent)

The result should be this from the Filecontent string:

 ESPAÑA_BOLSA.xlsx

What I'm doing wrong? thanks, I accept suggestions

Esraa_92
  • 1,558
  • 2
  • 21
  • 48
  • 2
    Have a look at [this](http://stackoverflow.com/questions/18915633/determine-textfile-encoding) – Kilazur Sep 28 '16 at 14:40
  • Thank you very much for your contribution – Esraa_92 Sep 28 '16 at 14:54
  • It's probably an encoding issue as mentioned below, but you should also change your code, you created a memory leak by not closing your stream reader. Research "Using-statements" in VB for the cleanest solution – Joost Aarts Sep 28 '16 at 15:03

1 Answers1

3

You need to use the StreamReader constructor that takes an Encoding, and pass in the appropriate encoding - otherwise it will default to using UTF-8. Encoding.Default may work, otherwise you will need to use specific encoding. I don't know how your file is encoded, so can't tell you the exact value you need, but you could try:

Dim sr As StreamReader = New StreamReader(FilePath, System.Text.Encoding.Default)
' or, as an example - you may need a different encoding
Dim sr As StreamReader = New StreamReader(FilePath, System.Text.Encoding.GetEncoding("Windows-1252"))
Mark
  • 8,140
  • 1
  • 14
  • 29