Esraa_92 Esraa_92 - 8 months ago 62 Question

Decode text from .txt file

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


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


So I have this code in 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:


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:


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


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"))