【问题标题】:memorystream not saving all contentmemorystream 不保存所有内容
【发布时间】:2012-02-25 00:55:56
【问题描述】:

在 c# 中遇到了内存流的大问题。我的应用程序获取电子邮件的 html,并解析作为附件的图像的 src 值并将这些 src 值更改为另一个值。这工作得很好。问题是我必须将生成的 html 保存在共享点列表中。确实如此,但是当我看到共享点列表中的内容时,它不显示电子邮件,只是其中的一部分。我不知道内存流是否根本没有保存内容,或者字符串正在保存结果是否没有足够的容量来保存内存流正在存储的内容。如果有人有任何想法,请发表!

string SRC = "";
int indice = 0;
//Console.WriteLine(body);

HtmlDocument email = new HtmlDocument();
email.LoadHtml(body);
Console.WriteLine("bodylength: " + body.Length);//original length

foreach (HtmlNode img in email.DocumentNode.SelectNodes("//img"))
{
    SRC = img.GetAttributeValue("src", null);
    for (int i = 0; i < contentIDS.Count; i++)
    {
        if (SRC.Equals(contentIDS[i].ToString()))
        {
            //Console.WriteLine("contents" + contentIDS[i].ToString());
            indice = i;
            break;
        }
    }
    img.SetAttributeValue("src", urls[indice].ToString());
    Console.WriteLine(img.GetAttributeValue("src", null));
}

//se guarda en memoria los cambios hechos en el html y se retorna e tipo string el html con los cambios realizados
MemoryStream memoryStream = new MemoryStream();
email.Save(memoryStream);
//memoryStream.SetLength(body.Length);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
StreamReader streamReader = new StreamReader(memoryStream);
return streamReader.ReadToEnd();//this is then store in a string when i call this method. The lenght of that string is much much smaller than the original one.

【问题讨论】:

  • 也许尝试将 MemoryStream 的使用情况包装在 using() 块中?
  • 您确定这不仅仅是 HTML 渲染问题吗?你看网页源码了吗?有完整的电子邮件吗?
  • 请不要在标题中添加“c#”等。这就是标签的用途。
  • 这是您使用的 Html Agility Pack?
  • 这是哪个 HtmlDocument? msdn.microsoft.com/en-us/library/…msdn.microsoft.com/en-us/library/… 都没有 Save(Stream) 方法。

标签: c# html-agility-pack memorystream


【解决方案1】:

您可以通过使用Save 重载来简化此操作,该重载使用TextWriter

HtmlDocument email = new HtmlDocument();
using (var sw = new StringWriter())
{
    email.Save(sw);
    return sw.ToString();
}

请注意,您应该始终处置实现IDisposable 的对象(最简单的方法是将它们包装在using 块中,如此处所示)。

【讨论】:

  • 感谢它以这种方式工作并将html保存在其全部内容中!非常感谢
  • 我实际上从未使用过这个库,我只是浏览了source codeHtmlDocument 类,看看是否有更方便的重载。可惜没有ToString 重载(与LoadHtml 相对,您可以直接从字符串加载)。
【解决方案2】:

我的怀疑是你把整个字符串都放回了这里,而不是Flush()在其他地方输入一个流——可能是当你将它保存到磁盘时。这里的代码看起来不错。

如果你将函数发布到你保存它的地方,我猜我们会在那里看到问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2021-09-27
    • 1970-01-01
    • 2022-09-24
    • 2010-11-07
    相关资源
    最近更新 更多