【问题标题】:opening binary files from SQL using LINQ使用 LINQ 从 SQL 打开二进制文件
【发布时间】:2014-06-28 02:23:12
【问题描述】:

我正在使用二进制文件将我的 word/excel/pdf/Img 文件保存在 SQL 中,并且我能够成功地将文件保存为二进制文件。

var fileSize = FileUpload1.PostedFile.ContentLength;
var documentBinary = new byte[fileSize];
var u = new UDocument
                {
                    DocName = fileName.ToString(CultureInfo.InvariantCulture),
                    Type = documentType.ToString(CultureInfo.InvariantCulture),
                    DocData = documentBinary
                };
                u.DocID = ++count;
                sd.UDocuments.InsertOnSubmit(u);
                sd.SubmitChanges();

现在,我正在尝试将二进制文件作为他们的文档类型打开,并且我正在从显示所有存储文件的网格视图中打开它。

现在,在 Gridview SelectedIndexChange 事件中,我可以获取文档 ID、文档名称,以便我打开文件,但我不清楚如何从文档 ID(即 PK)中获取二进制数据,以及如何写出文件。这是我试图让它发挥作用的方法:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int docid = Convert.ToInt16(GridView1.SelectedRow.Cells[1].Text);
        string name = GridView1.SelectedRow.Cells[2].Text;
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + name);
        Response.BinaryWrite(GetData(docid)); // I am unclear on how to use this method, with the 
        Response.Flush();
    }

在我的 GetData(int id) 方法中,我尝试使用 LINQ 通过唯一的 docID 获取正确的二进制数据,如下所示:

var data = from a in sd.UDocuments
            where a.DocID == id
            select a.DocData

但我不确定在此方法中使用什么返回类型。

任何帮助或指示都会很棒。

【问题讨论】:

    标签: c# asp.net linq binaryfiles


    【解决方案1】:

    GetData 的返回类型应与您的DocData 属性的类型相同,即byte[]

    【讨论】:

    • 我说得太早了,但是 +1 因为你让我重新审视我之前的方法..private byte[] GetData(int id) { byte[] data = (from a in sd .UDocuments where a.DocID == id select a.DocData).First().ToArray();返回数据; }
    【解决方案2】:
     private byte[] GetData(int id)
        {
            byte[] data = (from a in sd.UDocuments
                where a.DocID == id
                select a.DocData).First().ToArray();
           return data;
        }
    
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int docid = Convert.ToInt16(GridView1.SelectedRow.Cells[1].Text);
            string name = GridView1.SelectedRow.Cells[2].Text;
            string contentType = GridView1.SelectedRow.Cells[3].Text;
    
            Response.Clear();
            Response.ContentType = contentType; //"application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + name);
            Response.BinaryWrite(GetData(docid));
            Response.End();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2016-09-09
      • 2015-07-19
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      相关资源
      最近更新 更多