![](/img/trans.png)
[英]How to insert a list of values into SQL Server 2008 from asp.net using C#
[英]How to insert List<> values into SQL Binary field using C#
我对编程并不完全陌生,但我仍然认为自己是新手。 我目前正在创建一个最多包含5个订单项的发票系统,也就是说,我正在创建一个String <>项目,将其序列化以存储,然后反序列化以显示。 到目前为止,我已经管理了序列化和反序列化,并且从反序列化的值中,我设法在正确的字段中显示相关信息。
我的问题是:如何将String <>对象中的项目列表添加到SQL表的Binary或XML字段中? 我知道这应该类似于将Image对象添加到二进制文件中,但是这里有一个陷阱。 通常:
byte[] convertToByte(string sourcePath)
{
//get the byte file size of image
FileInfo fInfo = new FileInfo(sourcePath);
long byteSize = fInfo.Length;
//read the file using file stream
FileStream fStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
//read again as byte using binary reader
BinaryReader binRead = new BinaryReader(fStream);
//convert image to byte (already)
byte[] data = binRead.ReadBytes((int)byteSize);
return data;
}
此类操作是针对图像完成的,但是整个“长”操作不适用于List <>对象。
任何帮助都会有所帮助
如果只想将数据存储为“可读”文本,则可以使用varchar(MAX)
或nvarchar(MAX)
(取决于您是否需要扩展字符支持)。 它将直接转换为ADO.NET或EntityFramework中的字符串。
如果您只需要字符串中的字节,则Encoding类将执行以下操作:
System.Text.Encoding.Default.GetBytes(yourstring);
请参阅: http : //msdn.microsoft.com/en-us/library/ds4kkd55%28v=vs.110%29.aspx
将二进制文件保存为字符串的一种方法是将图像转换为Base64字符串。 这可以通过Convert.ToBase64String(Byte [])方法完成:
string convertImageToBase64(string sourcePath)
{
//get the byte file size of image
FileInfo fInfo = new FileInfo(sourcePath);
long byteSize = fInfo.Length;
//read the file using file stream
FileStream fStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
//read again as byte using binary reader
BinaryReader binRead = new BinaryReader(fStream);
//convert image to byte (already)
byte[] data = binRead.ReadBytes((int)byteSize);
return Convert.ToBase64String (data);
}
现在,您将能够在数据库的字符串字段中保存Base64字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.