【问题标题】:How to insert binary stream into varbinary? [duplicate]如何将二进制流插入varbinary? [复制]
【发布时间】:2020-03-06 19:56:04
【问题描述】:

我一直在阅读herehere 关于如何将二进制数组插入varbinary,但是如果我没有准备好字节数组怎么办?如果我要序列化一个对象怎么办?所以如果我有

var Formatter = new BinaryFormatter();
Formatter.Serialize(SerializeStream, NewEmployeeTree);

当我想序列化成文件时,我将SerializeStream 传递为

 var SerializeStream = new FileStream(SelectedPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

但是这次我想序列化到数据库中。我该怎么做?

【问题讨论】:

  • @RobertHarvey 但是我怎样才能在我的代码中实现它呢?
  • 您的问题是“如果我没有准备好字节数组怎么办?”链接的帖子解释了如何将流转换为字节数组。一旦你这样做了,你将准备好一个字节数组。
  • @RobertHarvey 但是我从哪里得到流?什么类型的流?

标签: c# sql-server tsql serialization


【解决方案1】:

你可以使用

批量插入

像这样:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
   class Program
   {
       static void Main(string[] args)
       {
           //toturial obj = new toturial();
           //obj.ID = 1;
           //obj.name = "MrLotfi";
           //IFormatter formatter = new BinaryFormatter();
           //Stream stream = new FileStream("E:\\example.txt", FileMode.Create, FileAccess.ReadWrite);
           //formatter.Serialize(stream,obj);
           //stream.Close();
           Tutorial obj = new Tutorial();
           obj.ID = 1;
           obj.Name = ".Net";
           IFormatter formatter = new BinaryFormatter();
           Stream stream = new FileStream(@"E:\ExampleNew.txt", FileMode.Create, FileAccess.Write);
           formatter.Serialize(stream, obj);
           stream.Close();
           SqlConnection conn = new SqlConnection("Your SQL Connection String");
           conn.Open();
           StringBuilder str = new StringBuilder();
           str.AppendLine("DECLARE @tImage AS VARBINARY(MAX)");
           str.AppendLine(@"SELECT @tImage = CAST(bulkcolumn AS VARBINARY(MAX)) FROM OPENROWSET( BULK 'E:\ExampleNew.txt', SINGLE_BLOB ) AS x");
           str.AppendLine(@"INSERT INTO TblPhotos (ID, Name, Images) SELECT NEWID(), 'E:\ExampleNew.txt',@tImage");
           SqlCommand cmd = new SqlCommand(str.ToString(), conn);
           cmd.ExecuteNonQuery();
           Console.WriteLine("Image Saved Successfully...");
           stream = new FileStream(@"E:\ExampleNew.txt", FileMode.Open, FileAccess.Read);
           Tutorial objnew = (Tutorial)formatter.Deserialize(stream);
           Console.WriteLine(objnew.ID);
           Console.WriteLine(objnew.Name);
           Console.ReadKey();
       }
   }
   [Serializable]
   public class Tutorial
   {
       public int ID;
       public string Name;
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 2017-01-26
    • 2011-04-13
    • 1970-01-01
    • 2010-11-10
    • 2021-12-22
    • 2015-06-09
    • 2015-07-22
    相关资源
    最近更新 更多