c#中的对象引用错误 [英] Object reference error in c#

查看:105
本文介绍了c#中的对象引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用json库和公共API密钥创建一个virustotal上传器和扫描器。



当我上传文件进行扫描时,上传完成后我收到错误。



I am making a virustotal uploader and scanner using json library and public api key.

when i upload file for scanning,after uploading completes i get an error.

public void sendAndScanFile(string nFileName)
        {
            this.file_name = nFileName;
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("key", this.vt_apikey);
            nvc.Add("scan", "1");
            string r = httpUploadFile("https://www.virustotal.com/api/scan_file.json", this.file_name, "file", "application/exe", nvc);

            JObject o = JObject.Parse(r);
            string scan_id = (string)o["scan_id"];
            string[] s = scan_id.Split('-');
            getScanReport(s[0]);
        }







错误上升的行是






The line at which error rises is

Quote:

string [] s = scan_id.Split(' - ');

string[] s = scan_id.Split('-');





错误详情



System.NullReferenceException未被用户代码处理

消息=对象引用未设置为对象的实例。



error details

System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.

推荐答案

它出错,因为 scan_id 。首先,检查它是否为空,如果不是,则拆分并获取扫描报告:

It gives an error because scan_id is null. First, check whether it is null, and if it isn't, split and get the scan report:
if (scan_id != null) // check for null
{
    string[] s = scan_id.Split('-');
    if (s.Length > 0) // only get report if the array contains elements
    {
        getScanReport(s[0]);
        return;
    }
}
// Put your code to handle null or empty array here. This code won't be executed if the array length was greater than 0, due to the return statement


对于字符串,还有另一个更好检查null和空的方法。这是 String.IsNullOrEmpty Method [ ^ ]。

For string, there is another better way to check for null and empty. That is String.IsNullOrEmpty Method[^].
Quote:

IsNullOrEmpty 是一种便捷方法,可让您同时测试 字符串 null 或其值 清空

IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is null or its value is Empty.



因此,只需对 ProgramFOX 提供的代码进行快速修改。


So, just a quick modification to the code provided by ProgramFOX.

if (!String.IsNullOrEmpty(scan_id)) // check for null and empty
{
   // Other code follows...
}


这篇关于c#中的对象引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆