从SQL数据库检索varbinary数据字段

问题描述:

我正在将数据存储在数据库中,这是我使用的代码,它在添加数据时起作用,但现在我想要恢复它。我怎样才能做到这一点?从SQL数据库检索varbinary数据字段

string filename = FileUploader.PostedFile.FileName; 
    string filecontent = FileUploader.PostedFile.ContentType; 
    int filesize = FileUploader.PostedFile.ContentLength; 

    string filepath = System.IO.Path.GetFileName(filename); 


    FileUploader.PostedFile.SaveAs("c:\\try\\" + filepath); 

    byte[] fileData = new byte[FileUploader.PostedFile.ContentLength]; 
    FileUploader.PostedFile.InputStream.Read(fileData, 0, fileData.Length); 
    string originalName = Path.GetFileName(FileUploader.PostedFile.FileName); 


    con.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["FAQ"].ToString(); 

    con.Open(); 

    using (SqlCommand cmd = new SqlCommand("INSERT INTO Files(FileData) VALUES (@binaryValue)", con)) 
    { 
     // Replace 8000, below, with the correct size of the field 
     cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, fileData.Length).Value = fileData; 
     cmd.ExecuteNonQuery(); 
     con.Close(); 
    } 

可以使用SqlDataReader获得的价值,并BinaryWriter创建文件,像这样:

//Database connection code... 
cmd.CommandText = "SELECT FileData FROM Files WHERE ID = @ID"; 
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = 1234; 
SqlDataReader sqlRead = cmd.ExecuteReader(); 

string fileName = "file.txt"; 
string fileDir = "C:\\Test\\"; 
string fileUrl = "/"; 

if (sqlRead.HasRows) 
{ 
    while(sqlRead.Read()) 
    { 
     byte[] fileData = (byte[]) sqlRead[0].Value; 
     BinaryWriter fileCreate = 
      new BinaryWriter(File.Open(fileDir + fileName, FileMode.Create)); 
     fileCreate.Write(fileData); 
     fileCreate.Close(); 
     HttpResponse.Redirect(fileUrl + fileName); 
    } 
} 

sqlRead.Close(); 
+0

感谢的人。但是,如果我在问题中添加了某些内容,请不要介意。 我怎样才能把这个日期放在一个文件中并下载这个文件?提前致谢。 – 2009-07-08 13:54:37