简体   繁体   English

如何将内存流转换为System.Data.Linq.Binary?

[英]How to convert Memory Stream to System.Data.Linq.Binary?

I just need to do the reverse conversion as exposed in this question . 我只需要进行反向转换即可解决此问题

I have a MemoryStream and want to store it in a System.Data.Linq Binary field of my SQL CE database (FYI I'm using EF code first). 我有一个MemoryStream,并想将其存储在我的SQL CE数据库的System.Data.Linq Binary字段中(仅供参考,我先使用EF代码)。

The MemoryStream is actually a XML, which is larger than the max size of a String field, so I found no other way than storing it in a Binary (suggestions on this subject REALLY appreciated). MemoryStream实际上是XML,它大于String字段的最大大小,因此我发现除了将其存储在Binary中别无他法(对此主题的建议非常感谢)。

My code (adapted) 我的代码(适应)

   private Stream _userLayout;
   _userLayout = new MemoryStream();
   DXGridControl_Table.SaveLayoutToStream(_userLayout);
   MyDatabse.SomeTable.SomeBinaryField = _userLayout.????

MemorySteam class has ToArray() method: MemorySteam类具有ToArray()方法:

MemoryStream.ToArray Method : MemoryStream.ToArray Method

Writes the stream contents to a byte array, regardless of the Position property. 不管Position属性如何,将流内容写入字节数组。

This method returns a copy of the contents of the MemoryStream as a byte array. 此方法以字节数组形式返回MemoryStream内容的副本。 If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned. 如果当前实例是在提供的字节数组上构造的,则返回该实例有权访问的数组部分的副本。 See the MemoryStream constructor for details. 有关详细信息,请参见MemoryStream构造函数。

This method works when the MemoryStream is closed. 当MemoryStream关闭时,此方法有效。

With byte[] you can easily get Binary instance, because Byte[] to Binary implicit conversion is available: 使用byte[]可以轻松获得Binary实例,因为Byte[]可以进行Binary隐式转换

MyDatabse.SomeTable.SomeBinaryField = (Binary) _userLayout.ToArray();

First there is 首先有

        byte[] buffer = new byte[LENGTH];
        MemoryStream memoryStream  = new MemoryStream(buffer);

In your example you can use 在您的示例中,您可以使用

        DXGridControl_Table.SaveLayoutToStream(_userLayout);
        byte[] doSomethingwithyourData = _userLayout.GetBuffer();
        var length = _userLayout.Length;

With that information you can write the binary data to whatever. 利用这些信息,您可以将二进制数据写入任何内容。

Note that the buffer contains allocated bytes which might be unused. 请注意,缓冲区包含分配的字节,这些字节可能未使用。 For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. 例如,如果将字符串“ test”写入MemoryStream对象,则从GetBuffer返回的缓冲区的长度为256,而不是4,未使用252个字节。 To obtain only the data in the buffer, use the ToArray method; 要仅获取缓冲区中的数据,请使用ToArray方法。 however, ToArray creates a copy of the data in memory. 但是,ToArray会在内存中创建数据的副本。

Or 要么

Binary binary = new Binary(_userLayout.ToArray());

Like in the other answer said, there is an implicit conversion on binary: 就像在其他答案中所说的那样,二进制有一个隐式转换:

public static implicit operator Binary(byte[] value) {
    return new Binary(value); 
}

You requested examples. 您要求提供示例。 A little example about the usage: 有关用法的一个小例子:

namespace Stackoverflow.Hannish.SaveLayout
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        /// <summary>
        /// Here we store the layout data as a string. This is the data, that
        /// gets saved to disk / database / etc.
        /// </summary>
        private string layoutdata = string.Empty;

        public Form1()
        {
            this.InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Just some FooBar data.
            var data = new List<DataValue>
                           {
                               new DataValue { Id = 1, Name = "Xyz", IsCool = true }, 
                               new DataValue { Id = 2, Name = "Abc", IsCool = false }
                           };

            this.gridControl1.DataSource = data;
        }

        private void bnLoadLayout_Click(object sender, EventArgs e)
        {
            using (var stream = new MemoryStream())
            {
                var strdata = Encoding.Default.GetBytes(this.layoutdata);
                stream.Write(strdata, 0, strdata.Length);
                stream.Seek(0, SeekOrigin.Begin);
                this.gridView1.RestoreLayoutFromStream(stream);
            }
        }

        private void bnSaveLayout_Click(object sender, EventArgs e)
        {
            using (var stream = new MemoryStream())
            {
                this.gridView1.SaveLayoutToStream(stream);
                this.layoutdata = Encoding.Default.GetString(stream.ToArray());
            }
        }
    }
}

And some byte to file magic: 和一些字节归档魔术:

    private void bnLoadBinLayout_Click(object sender, EventArgs e)
    {
        using (FileStream fstream = File.Open("Layoutdata.bin", FileMode.Open))
        {
            int length = (int)fstream.Length;
            byte[] buffer = new byte[length];
            fstream.Read(buffer, 0, length);

            var memstream = new MemoryStream(buffer);
            this.gridView1.RestoreLayoutFromStream(memstream);
        }
    }

    private void bnSaveBinLayout_Click(object sender, EventArgs e)
    {
        using (FileStream fstream = File.Create("Layoutdata.bin"))
        {
            var memstream = new MemoryStream();
            this.gridView1.SaveLayoutToStream(memstream);
            fstream.Write(memstream.GetBuffer(), 0, (int)memstream.Length);
        }
    }

... just as example. ...只是一个例子。 DevExpress GridView can save the layout itself with SaveLayoutToXml(); DevExpress GridView可以使用SaveLayoutToXml()保存布局本身。

To your second question and your (possible) conceptual mistake of converting the data back and forth. 对于您的第二个问题,以及您在(可能的)概念上来回转换数据的错误。

Save that funny DevExpress XML in a ntext data column. 将有趣的DevExpress XML保存在ntext数据列中。

ntext: Variable-length Unicode data with a maximum length of (2^30–2)/2 (536,870,911) characters. ntext:可变长度Unicode数据,最大长度为(2 ^ 30–2)/ 2(536,870,911)个字符。 Storage size, in bytes, is two times the number of characters entered. 存储大小(以字节为单位)是输入字符数的两倍。

See SQL Server Compact 4.0 Data Types 请参阅SQL Server Compact 4.0数据类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将&#39;byte []&#39;类型转换为&#39;System.Data.Linq.Binary&#39; - How to convert type 'byte[]' to 'System.Data.Linq.Binary' 在C#中,我如何从URL获取图像并转换为System.Data.Linq.Binary - in C#, how can i take an image from a URL and convert to System.Data.Linq.Binary 如何在C#中将System.Data.Linq.Binary分配为null? - How to assign System.Data.Linq.Binary to null in C#? 无法从“ System.DateTime”转换为“ System.Data.Linq.Binary”错误 - Cannot convert from 'System.DateTime' to 'System.Data.Linq.Binary' error 无法在LINQ中将类型&#39;string&#39;隐式转换为&#39;System.Data.Linq.Binary - Cannot implicitly convert type 'string' to 'System.Data.Linq.Binary in LINQ to SQL LINQ,聚合操作不支持“System.Data.Linq.Binary”类型 - The type 'System.Data.Linq.Binary' is not supported in aggregation operations - LINQ 将System.Drawing.Image转换为System.Data.Linq.Binary - Converting System.Drawing.Image to System.Data.Linq.Binary .NET Core中的等效System.Data.Linq.Binary - Equivalent System.Data.Linq.Binary in .net core 类型“ System.Data.Linq.Binary”在未引用的程序集中定义 - Type 'System.Data.Linq.Binary' is defined in an assembly that is not referenced 将SQL Server ROWVERSION放入System.Data.Linq.Binary属性时,出现System.InvalidCastException - System.InvalidCastException when getting SQL Server ROWVERSION into System.Data.Linq.Binary property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM