我的目标是将DICOM文件存储在具有某些ID的SQL Server中,当用户想要该DICOM文件时,他可以使用其相应的ID从SQL Server下载。存储到服务器时以及从SQL Server检索时,文件不应更改其原始性。我使用Varbinary(max)
数据类型来存储SQL Server中DICOM文件的字节数组。我正在将DICOM文件的内存流转换为字节数组,然后存储到SQL服务器中,如下所述:
using (MemoryStream memStream = new MemoryStream())
{
using (FileStream fileStream = File.Open(txtDICOMFilePath.Text, FileMode.Open))
{
// Copy the file stream to memory stream.
fileStream.CopyTo(memStream);
}
int intL = Convert.ToInt32(memStream.Length);
byte[] objData = new byte[intL];
}
//Set insert query
string qry = "insert into ImagesStore (ID,ImageData) values(@ID, @ImageData)";
//Initialize SqlCommand object for insert.
SqlCommand SqlCom = new SqlCommand(qry, CN);
//We are passing Original Image Path and Image byte data as sql parameters.
SqlCom.Parameters.Add(new SqlParameter("@ID", (object)txtUniqueID.Text));
SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)objData));
//Open connection and execute insert query.
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
问题: 在存储Image时,它可以正确存储(没有任何异常),但在检索它时不会提供准确的数据。任何正文可以帮助我将DICOM文件存储在SQL服务器中而不会有任何损失吗?
更新 下面是我下载DICOM文件的代码。
qry = "select ImageData from ImagesStore where ID= @ID";
//Initialize SqlCommand object for insert.
SqlCom = new SqlCommand(qry, CN);
SqlCom.Parameters.Add("@ID", SqlDbType.Int).Value = (object)txtUniqueID.Text;
SqlDataAdapter adp = new SqlDataAdapter(SqlCom);
DataTable dt = new DataTable();
try
{
if (CN.State == ConnectionState.Closed)
CN.Open();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["ImageData"]);
//Logic to save the file
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
}
答案 0 :(得分:1)
在使用block之前和之前声明byte[] objData
并尝试设置字节数组的 size :
byte []objData=null;
using (MemoryStream memStream = new MemoryStream())
{
using (FileStream fileStream = File.Open(txtDICOMFilePath.Text, FileMode.Open))
{
fileStream.CopyTo(memStream);
}
int intL = Convert.ToInt32(memStream.Length);
objData = new byte[intL];
memStream.Read(objData,0,objData.Length);
}
SqlCom.Parameters.Add("@ImageData",SqlDb.Image,objData.Length).Value=objData;
编辑:从ImagesStore
string qry = "select * From ImagesStore";
using(SqlConnection Cn=new SqlConnect(CnStr))
{
using(SqlCommand SqlCom = new SqlCommand(qry, CN))
{
Cn.Open();
using(SqlDataReader dr=SqlCom.ExecuteReader())
{
while(dr.Read())
{
string path="x:\\folder\\" + dr[0] + ".png";
byte []bytes=(byte[])dr[1];
System.IO.File.WriteAllBytes(path,bytes);
}
}
}
}
或者,您可以使用DataAdapter / DataTable(OP中的代码)
if (dt.Rows.Count > 0)
{
foreach(DataRow row in dt.Rows)
{
string path="x:\\folder\\" + row[0] + ".png";
byte []bytes=(byte[])row[1];
System.IO.File.WriteAllBytes(path,bytes);
}
}