c# - 如何检查字节数组是否为空?

标签 c#

我正在为 GetSourceAttachment 方法下载 word 文件。当此方法返回空字节时,我的字节 Attachment 数组会出错:

Object reference not set instance of object

当我在 if 条件下检查 Attachment 的长度时出现错误。

谁能帮我默认初始化字节数组,然后检查长度?

try
{
        byte[] Attachment = null ;

        string Extension = string.Empty;
        ClsPortalManager objPortalManager = new ClsPortalManager();
        Attachment = objPortalManager.GetSourceAttachment(Convert.ToInt32(hdnSourceId.Value), out Extension);
        if (Attachment.Length > 0 && Attachment != null)
        {
            DownloadAttachment("Attacment", Attachment, Extension);
        }
        else
        {
            ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Attachment is not Uploaded !');</script>");
        }            
}
catch
{

}

最佳答案

就这样

if (Attachment != null  && Attachment.Length > 0)

来自 && Operator

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

关于c# - 如何检查字节数组是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16476267/

相关文章:

c# - 在任务取消时处理 CancellationTokenSource 的代码是否正确?

c# - 检查 T 是否实现接口(interface)并在填充接口(interface)属性后返回 T

c# - 转换所有参数、返回类型、类定义以使用接口(interface)

c# - 在运行时更改 WPF DataGrid 整个列的背景颜色

c# - 如何在 ASP.NET MVC 中获取错误状态代码

c# - Class "object"中的 == 运算符在哪里定义?

c# - Xamarin 与原生 iOS 和 Android

c# - 我可以从 MethodDefinition (Cecil) 获取 MethodInfo 吗?

c# - 如何在像素着色器中实现 super 采样/抗锯齿?

c# - 如何创建和使用自己的 C++ 函数而不是内置的库