gpt4 book ai didi

c# - 无法访问已关闭的流 ASP.net v2.0

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:07 24 4
gpt4 key购买 nike

我们有一个非常奇怪的问题,下面的代码在所有开发人员机器/我们的 2 个测试服务器上运行良好,无论是代码还是构建版本,但是当它在具有 Windows 2003 服务器和 asp 的虚拟机上运行时。 net v2.0 它抛出一个错误

Cannot access a closed stream.

public String convertResultToXML(CResultObject[] state)
{
MemoryStream stream = null;
TextWriter writer = null;
try
{
stream = new MemoryStream(); // read xml in memory
writer = new StreamWriter(stream, Encoding.Unicode);
// get serialise object
XmlSerializer serializer = new XmlSerializer(typeof(CResultObject[]));
serializer.Serialize(writer, state); // read object
int count = (int)stream.Length; // saves object in memory stream
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
// copy stream contents in byte array
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding(); // convert byte array to string
return utf.GetString(arr).Trim();
}
catch
{
return string.Empty;
}
finally
{
if (stream != null) stream.Close();
if (writer != null) writer.Close();
}
}

知道为什么要这样做吗?

最佳答案

对于您的Serialize,使用using 来防止流保持打开

像这样:

using (StreamWriter streamWriter = new StreamWriter(fullFilePath))
{
xmlSerializer.Serialize(streamWriter, toSerialize);
}

关于c# - 无法访问已关闭的流 ASP.net v2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9737893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com