【问题标题】:Decode text from .txt file asp.net?从.txt文件asp.net解码文本?
【发布时间】:2017-02-06 14:42:47
【问题描述】:

我的网络项目中有一个包含此文件的目录:

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

但是通过这段代码,我在 Filecontent 中得到了这个结果:

ESPA�A_BOLSA.xlsx

所以我用这一行来尝试解码文本,但不起作用:

  FileContent = WebUtility.HtmlDecode(FileContent)

结果应该是来自 Filecontent 字符串:

 ESPAÑA_BOLSA.xlsx

我做错了什么?谢谢,我接受建议

【问题讨论】:

  • 看看this
  • 非常感谢您的贡献
  • 这可能是下面提到的编码问题,但您也应该更改您的代码,您没有关闭流阅读器造成了内存泄漏。在 VB 中研究“使用语句”以获得最干净的解决方案

标签: c# asp.net vb.net decode


【解决方案1】:

您需要使用带有EncodingStreamReader 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"))

【讨论】:

  • 你的代码对我来说很完美,比你的时间要多:-)
猜你喜欢
  • 2020-10-02
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多