gpt4 book ai didi

c# - 创建 MTOM 并反序列化它

转载 作者:行者123 更新时间:2023-11-30 15:04:14 24 4
gpt4 key购买 nike

我一直在使用一些代码通过使用来自 MSDN 的代码来创建 MTOM .

好像有错误,我不明白问题出在哪里,因为论坛上的一位用户指出有错误。

文件 (JPEG) 数据在反序列化后损坏。完整代码如下。

 public class Post_7cb0ff86_5fe1_4266_afac_bcb91eaca5ec
{
[DataContract()]
public partial class TestAttachment
{
private byte[] fileField;
private string filenameField;

[DataMember()]
public byte[] File
{
get
{
return this.fileField;
}
set
{
this.fileField = value;
}
}
[DataMember()]
public string Filename
{
get
{
return this.filenameField;
}
set
{
this.filenameField = value;
}
}
}
public static void Test()
{
string Filename = "Image.jpg";
byte[] file = File.ReadAllBytes(Filename);

TestAttachment Attachment = new TestAttachment();
Attachment.Filename = Filename;
Attachment.File = file;
MemoryStream MTOMInMemory = new MemoryStream();
XmlDictionaryWriter TW = XmlDictionaryWriter.CreateMtomWriter(MTOMInMemory, Encoding.UTF8, Int32.MaxValue, "");
DataContractSerializer DCS = new DataContractSerializer(Attachment.GetType());
DCS.WriteObject(TW, Attachment);
TW.Flush();
Console.WriteLine(Encoding.UTF8.GetString(MTOMInMemory.ToArray()));
var v = DeserializeMTOMMessage(Encoding.UTF8.GetString(MTOMInMemory.ToArray()));
File.WriteAllBytes(v.Filename,v.File);
}

public static TestAttachment DeserializeMTOMMessage(string MTOMMessage)
{

try
{

MemoryStream MTOMMessageInMemory = new MemoryStream(UTF8Encoding.UTF8.GetBytes(MTOMMessage));

XmlDictionaryReader TR = XmlDictionaryReader.CreateMtomReader(MTOMMessageInMemory, Encoding.UTF8, XmlDictionaryReaderQuotas.Max);

DataContractSerializer DCS = new DataContractSerializer(typeof(TestAttachment));

return (TestAttachment)DCS.ReadObject(TR);

}
catch
{

return null;

}

}
}

如果有人能帮我指出问题所在,我将不胜感激。我是 XOP/MTOM 的新手,发现很难找出错误可能出在哪里。序列化或反序列化。

谢谢

最佳答案

您的代码中存在错误。改变你的方法调用

MTOMInMemory.Position = 0;
DeserializeMTOMMessage(Encoding.UTF8.GetString(MTOMInMemory.ToArray()));

DeserializeMTOMMessage(MTOMInMemory.ToArray())

和实现

 public static TestAttachment DeserializeMTOMMessage(byte[] MTOMMessage) 
{
try
{
MemoryStream MTOMMessageInMemory = new MemoryStream(MTOMMessage);
XmlDictionaryReader TR = XmlDictionaryReader.CreateMtomReader(MTOMMessageInMemory, Encoding.UTF8, XmlDictionaryReaderQuotas.Max);
DataContractSerializer DCS = new DataContractSerializer(typeof(TestAttachment));
return (TestAttachment)DCS.ReadObject(TR);
}
catch
{

return null;
}
}

您所做的是从 utf8 到字节数组的双重转换,反之亦然,最终创建的不是您使用的原始字节数组

关于c# - 创建 MTOM 并反序列化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10551228/

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