首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用可变二进制数据生成文本文件

如何用可变二进制数据生成文本文件
EN

Stack Overflow用户
提问于 2014-04-05 02:11:05
回答 2查看 1.1K关注 0票数 1

我尝试从SQL Server检索varbinary值数组,而不是尝试将它们存储在一个文本文件中,用户可以下载该文件,但不确定如何将该文件返回到Response.Redirect()或如何返回该文本文件。

代码语言:javascript
运行
复制
public byte[] GenerateTextFile()
{
    if (m_Template == CFCTemplate.GETTXTDATA)
    {
       SqlCommand cmd = new SqlCommand("SELECT SpecData FROM Spec WHERE TestID=" + SpecTestID);
       InternalSalesDB.Instance.query(cmd);

       DataTable dt = InternalSalesDB.Instance.query(cmd).Tables[0];

       if (dt.Rows.Count > 0)
       {
           byte[] binarySpec = (byte[])dt.Rows[0][0];

           FileStream fileStream = new FileStream("TestData.txt",FileMode.Append);  
           fileStream.Write(binarySpec, 0, binarySpec.Length);
           fileStream.Flush();
           fileStream.Close();
      }
    }
   //need return statement here ??
}
EN

回答 2

Stack Overflow用户

发布于 2014-04-05 02:23:11

希望这将有助于获得一个想法。在这里,它从数据表创建一个CSV文件,并使用Respose下载它。

代码语言:javascript
运行
复制
private void WriteToCSV(DataTable dt, string fileName, string delimiter)
{
    // Prepare the Output Stream
    Response.Clear();
    Response.ContentType = "text/csv";
    Response.AppendHeader("Content-Disposition",
        string.Format("attachment; filename={0}", fileName));

    string value = "";
    StringBuilder builder = new StringBuilder();

    // Write the CSV Column Headers
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        value = dt.Columns[i].ColumnName;
        // Implement special handling for values that contain comma or quote
        // Enclose in quotes and double up any double quotes
        if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
            builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
        else
        {
            builder.Append(value);
        }

        Response.Write(value);
        Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
        builder.Clear();
    }

    //write the data
    foreach (DataRow row in dt.Rows)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            value = row[i].ToString();
            // Implement special handling for values that contain comma or quote
            // Enclose in quotes and double up any double quotes

            if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
                builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
            else
            {
                builder.Append(value);

            }

            Response.Write(builder.ToString());
            Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
            builder.Clear();
        }
    }

    Response.End();
}
票数 1
EN

Stack Overflow用户

发布于 2014-04-05 02:49:55

为什么不让用户直接以文本文件的形式下载varbinary呢?

使用通用处理程序(.ashx)很容易完成,当您从项目>添加>新建项添加通用处理程序时,模板提供了大部分代码...>通用处理程序

代码语言:javascript
运行
复制
Public Class DocHandler
  Implements IHttpHandler, IRequiresSessionState

声明一个字节数组

代码语言:javascript
运行
复制
  Dim buffer() As Byte

context参数允许您在需要时访问会话数据。在本例中,我访问了文件名,但这可以很容易地从DB调用或处理程序的url参数中获取。

代码语言:javascript
运行
复制
  Sub ProcessRequest(ByVal context As HttpContext) _
    Implements IHttpHandler.ProcessRequest

    If context.Response.IsClientConnected Then
      If context.Request.UrlReferrer IsNot Nothing Then
        If context.Session("case_document_key") IsNot Nothing Then

在这里初始化DB调用,我假定有一个名为Cmd的SqlCommand变量

代码语言:javascript
运行
复制
          Dim yourvarbinaryfield = Cmd.ExecuteScalar()

将返回的varbinary字段转换为字节数组buffer =DirectCast(您的yourvarbinaryfield,Byte())

这就是魔术。

将处理程序响应头内容部署设置为以文本形式下载文件:

代码语言:javascript
运行
复制
          context.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", context.Session("YourFileName")))
          context.Response.ContentType = "text/plain"
          context.Response.BinaryWrite(buffer)
          context.Response.OutputStream.Write(buffer, 0, buffer.Length)
          context.Response.Flush()

        End If
      End If
    End If
  End If
End Sub

ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
  Get
      Return False
  End Get
End Property

结束类

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22870111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档