如何将VARBINARY列中存储的文件保存到文件夹中?

时间:2018-10-31 19:49:02

标签: c# asp.net-web-api

我将文件以表中VARBINARY列的形式存储到SQL Server中。 在这里,我尝试获取该内容并将其作为文件保存到文件夹中:

List<FileData> newData = new List<FileData>();

var c = from n in db.FileTable
        where n.Id == 1
        select n;

foreach(var _somedata in c)
{
    var abc = new FileData
                {
                    _FileData = _somedata.FileData,
                    FileName = _somedata.FileName,
                };

    newData.Add(abc);
    string Img_name = abc.FileName;
    string folder_path = System.Web.HttpContext.Current.Server.MapPath("~/Images");

    if (!Directory.Exists(folder_path))
    {
        Directory.CreateDirectory(folder_path);
    }

    string imgPath = Path.Combine(folder_path, Img_name);
    ...
}

如何将文件存储到该文件夹​​中?

1 个答案:

答案 0 :(得分:0)

由于它是二进制文件,因此可以使用System.IO.File.WriteAllBytes()方法:

foreach(var _somedata in c)
{
    var abc = new FileData
                {
                    _FileData = _somedata.FileData,
                    FileName = _somedata.FileName,
                };

    string Img_name = abc.FileName;
    string folder_path = System.Web.HttpContext.Current.Server.MapPath("~/Images");

    if (!Directory.Exists(folder_path))
    {
        Directory.CreateDirectory(folder_path);
    }

    string imgPath = Path.Combine(folder_path, Img_name);

    // this call will write out all the bytes (content) of your file
    // to the file name you've specified   
    File.WriteAllBytes(imgPath, abc._FileData);
}