从 .txt 文件解码文本 asp.net?
Decode text from .txt file asp.net?
我的 web 项目中有一个包含此文件的目录:
home.text
在 home.txt 文件中我有这个文本:
ESPAÑA_BOLSA.xlsx
所以我在 vb.net 中有这段代码,用于从 .txt 文件中提取文本:
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
但是使用这段代码,我在文件内容中得到了这个结果:
ESPA�A_BOLSA.xlsx
所以我使用这一行来尝试解码文本,但是没有用:
FileContent = WebUtility.HtmlDecode(FileContent)
Filecontent 字符串的结果应该是这样的:
ESPAÑA_BOLSA.xlsx
我做错了什么?谢谢,我接受建议
您需要使用带有 Encoding
的 StreamReader
constructor,并传入适当的编码 - 否则它将默认使用 UTF-8。 Encoding.Default
可能有效,否则您将需要使用特定的编码。我不知道你的文件是如何编码的,所以不能告诉你你需要的确切值,但你可以试试:
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"))
我的 web 项目中有一个包含此文件的目录:
home.text
在 home.txt 文件中我有这个文本:
ESPAÑA_BOLSA.xlsx
所以我在 vb.net 中有这段代码,用于从 .txt 文件中提取文本:
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
但是使用这段代码,我在文件内容中得到了这个结果:
ESPA�A_BOLSA.xlsx
所以我使用这一行来尝试解码文本,但是没有用:
FileContent = WebUtility.HtmlDecode(FileContent)
Filecontent 字符串的结果应该是这样的:
ESPAÑA_BOLSA.xlsx
我做错了什么?谢谢,我接受建议
您需要使用带有 Encoding
的 StreamReader
constructor,并传入适当的编码 - 否则它将默认使用 UTF-8。 Encoding.Default
可能有效,否则您将需要使用特定的编码。我不知道你的文件是如何编码的,所以不能告诉你你需要的确切值,但你可以试试:
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"))