C# 从 SQLdatabase 检索 varbinary 数据字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1098022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:09:58  来源:igfitidea点击:

retrieve varbinary datafield from SQLdatabase

c#sql

提问by Ahmad Farid

i am storing files in database and this is the code i am using and it works in adding the data, but now i want to retrieve it back. how can i do that?

我将文件存储在数据库中,这是我正在使用的代码,它用于添加数据,但现在我想取回它。我怎样才能做到这一点?

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();
    }

采纳答案by Eric

You can use a SqlDataReaderto obtain the value, and BinaryWriterto create the file, like so:

您可以使用 aSqlDataReader来获取值,并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();