c# - 如何从 byte[] 数组转换为 html?

标签 c# html asp.net post

我正在使用 NameValueCollection 发布到网站。转换为字符串时的响应数组包含“\r\n”。我需要纯 html,所以我可以使用字符串在页面上显示内容。这是代码:

 byte[] responseArray = myWebClient.UploadValues(SubmitURL, myNameValueCollection);
 string s = Encoding.ASCII.GetString(responseArray);

s 包含这样的内容:

   \r\n    \r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n\r\n<head>\r\n<title>Transaction Code Search Results</title>\r\n<link href=\"searchreference.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n\r\n</head>\r\n\r\n<body topmargin=\"10\" leftmargin=\"10\">\r\n<table border=\"0\" width=\"100%\">\r\n  <tr>\r\n    <td width=\"70\" rowspan=\"2\" align=\"left\"><img src=\"images/WFLogo_62.gif\" alt=\"WF logo\" width=\"62\" height=\"62\" /></td>\r\n    <td height=\"40\">&nbsp;</td>\r\n    <td rowspan=\"2\"><form method=\"post\" action=\"trancodesearch3.asp\">\r\n      <div align=\"right\">\r\n        <input type=\"submit\" name=\"Search again\"\r\n      value=\"Search again\" />\r\n      </div>\r\n    </form></td>\r\n  </tr>\r\n  <tr>\r\n    <td valign=\"bottom\"><h1>Transaction Code Search Results</h1></td>\r\n  </tr>\r\n</table>\r\n\r\n<hr size=\"1\" class=\"redline\" />\r\n\r\n<table width=\"100%\" border=\"0\" align=\"
left\" cellpadding=\"6\"

最佳答案

您正在 Visual Studio 的调试器中查看 s 变量的值。这就是您看到所有这些 \r\n 符号的原因。实际上,这些只是字符串中包含的新行,您使用 Encoding.ASCII.GetString 方法将字节数组转换为字符串的代码是正确的。

您可以采用的一个小调整是编码本身。您可以使用 WebClient 使用 HTTP 响应 header 计算的编码:

byte[] responseArray = myWebClient.UploadValues(SubmitURL, myNameValueCollection);
string s = myWebClient.Encoding.GetString(responseArray);

因此,例如,如果远程网站支持与 ASCII 不同的编码,这将考虑到这一点,并且您不会在转换过程中丢失数据(您知道 ???? 符号,您希望得到一些重音符号例如字符)。

关于c# - 如何从 byte[] 数组转换为 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20338543/

相关文章:

c# - Papercut 中的附件

c# - 绑定(bind)运行次数可变的 RichTextBox

html - 标题垂直固定的滚动 Pane

c# - 存储过程报错

asp.net - 无法为 .net 安装 "LemmatizerPrebuiltCompact"库 - Visual Studio 错误

c# - .Net Core 3.1 HttpClient headers.TryAddWithoutValidation 不起作用

c# - 在图片框上创建平滑线(winforms,c#)

html - 如何在中心垂直对齐两个 div,并在底部保留一个 div?

html - 如何制作带有背景图像的垂直可调整大小的面板(chrome 中的缩放问题)

c# 将行添加到datagridview删除其他行的内容