日期:2014-05-19  浏览次数:20744 次

新手!在C#中如何将图片存到SQL中~!~
如何将图片存入SQL中在线等待~!~!希望能把关键代码发上来谢谢~!

------解决方案--------------------
using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;

class BLOBDemo
{
[STAThread]
static void Main(string[] args)
{
Add( "Test ", "1.jpg ");
}

public static void Add(string categoryName, string filePath)
{
// byte [] photo = GetPhoto(filePath);

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);

byte [] photo = br.ReadBytes((int)fs.Length);

br.Close();
fs.Close();

SqlConnection cn = new SqlConnection( "Data Source = (local);Integrated Security = SSPI;Initial Catalog=Northwind ");
SqlCommand cmd = new SqlCommand( "INSERT INTO Categories(CategoryName, Picture) VALUES (@CategoryName, @Picture) ", cn);

cmd.Parameters.Add( "@CategoryName ", SqlDbType.NVarChar, 15).Value = categoryName;
cmd.Parameters.Add( "@Picture ", SqlDbType.Image, photo.Length).Value = photo;

cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}

public static byte [] GetPhoto(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);

byte [] photo = br.ReadBytes((int)fs.Length);

br.Close();
fs.Close();

return photo;
}
}