【问题标题】:Unassigned Local Variable error when trying to download a file from database尝试从数据库下载文件时出现未分配的局部变量错误
【发布时间】:2014-06-12 01:20:32
【问题描述】:

我正在尝试从数据库下载文件,但它给了我一个名为 unaasigned local variable 的错误: 返回字节;

请告诉我如何将字符串转换为字节,提前谢谢。

我有一个名为 SaleFileName 的列,我想从中下载一个文件。

aspx代码:

<asp:TemplateField HeaderText="RecieptName" SortExpression="RecieptName">
                                <ItemTemplate>
                                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%# Bind("SaleFileName") %>' Text='<%# Bind("SaleFileName") %>' ></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>

文件背后的代码:

private byte[] ReadFileFromDatabase(string FileName) {
    string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;  
    byte[] bytes;

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "selectSaleFileName from Contributions where SaleFileName = @SaleFileName";
            cmd.Parameters.AddWithValue("@SaleFileName", FileName);
            cmd.Connection = con;
            con.Open();

            using ( SqlDataReader sdr = cmd.ExecuteReader())
            {
               if (sdr.Read() )
                  bytes = (byte[])sdr["SaleFileName"];
            }
            con.Close();
        }
    }

    return bytes; // This line is giving an error of unassigned error. Bytes is not assigned to anything it says.
    }
    protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            string FileName = Convert.ToString(e.CommandArgument);      
            byte[] bytes = ReadFileFromDatabase(FileName);

            Response.Clear()
            Response.ContentType = "application/octet-stream"
            Response.AddHeader("Content-Disposition", "attachment; FileName=" + FileName + ";");
            Response.BinaryWrite(bytes)
            Response.End()
        }
    }

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    编译器无法通过遵循静态代码流来确定是否会为bytes 分配任何值。

    您在 if 语句中初始化 bytes,如果没有从数据库返回的行怎么办,那么 bytes 将永远不会被初始化。

    您可以在声明时为您的bytes 分配一些默认值null,例如:

    byte[] bytes = null;
    

    上面的声明和初始化会消除错误,但是这完全取决于你的要求,是要抛出异常还是返回null。

    你可能还会看到:5.3 Definite assignment

    在函数成员的可执行代码中的给定位置, 如果编译器可以证明,变量被认为是绝对赋值的, 通过静态流分析,该变量已自动 已初始化或已成为至少一项分配的目标

    【讨论】:

    • 进行此更改后,在第二行最后一行,即 Response.BinaryWrite(bytes);它给出了一个名为 Object reference not set to an object 实例的错误。我应该改变什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2011-07-12
    • 1970-01-01
    • 2021-06-13
    • 2018-01-01
    相关资源
    最近更新 更多