字节数组 [英] Byte Array

查看:108
本文介绍了字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在将一些字节数组写入XElement以保存在XML文件中。
在某些情况下,此字节数组可能包含一个小图像。
<我按照以下方式进行:


Hello,

I am writing some Byte arrays to an XElement to save on a XML file.
In some cases this byte array might contain a small image.

I am doing it as follows:

      XElement node = new XElement("Node",
        new XElement("ByteTest1", Convert.ToBase64String(new Byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })),
        new XElement("ByteTest2", new Byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })
      );
      Console.WriteLine(node);



我得到以下内容:

<节点>
  < ByteTest1> AAECAwQFBgcICQ ==< / ByteTest1>
  < ByteTest2> 0123456789< / ByteTest2>
< / Node>

我应该使用Convert.ToBase64String吗?在哪种情况下我不应该使用它?如果我应该总是使用它是否可能,或者有意义,创建一个XElement扩展,当值为Byte []类型时,它使用Base64String?

谢谢,
Miguel


I get the following:

<Node>
  <ByteTest1>AAECAwQFBgcICQ==</ByteTest1>
  <ByteTest2>0123456789</ByteTest2>
</Node>

Should I use Convert.ToBase64String? In which case shouldn't I use it?
And if I should always use it is it possible, or it makes sense, to create a XElement extension that when the value is of type Byte[] it uses Base64String?

Thanks,
Miguel

推荐答案

你好,

你应该随时使用Base64以XML格式存储二进制数据(不一定是Base64,但无论如何都是一些编码)。请注意,通过这样做,使用该XML的应用程序将需要知道数据是这样编码的,并且在使用之前必须对其进行解码。
我不认为在一般情况下扩展XElement是一种简单的方法以你想要的方式行事的方式(你需要将Add方法设置为虚拟才能做到这一点,但事实并非如此)。但是你可以在一些简单的场景中使这个工作。例如,您可以像这样定义一个名为XBase64Element的派生类:
$
Hi,

You should use Base64 any time you want to store binary data in XML (doesn't have to be Base64, but some encoding like that anyway). Note that by doing so, the application consuming that XML will need to know that the data is encoded like that and will have to decode it before using.
I don't think there's an easy way to extend XElement in a general way to behave the way you want (you would need the Add methods to be virtual in order to do that, but they are not). But you could make this work for some simple scenarios. For example you coudl define a derived class called XBase64Element like this:
public class XBase64Element : XElement
{
    public XBase64Element(XName name, byte[] data)
        : base(name, Convert.ToBase64String(data))
    {
    }
}




然后在您的示例中,您只需使用新的XBase64Element替换新的XElement。请注意,在消费者方面这样做并不是那么容易。

谢谢,



Then in your sample you just replace the new XElement with new XBase64Element. Note that doing this on the consumer side would not be that easy though.

Thanks,


这篇关于字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆