1

大家好,我想像这样访问我的线程中的文件夹

protected string GetFolderName(int OrgID)
{
    string FolderName = string.Empty;
    string[] strDirectories = Directory.GetDirectories(HttpContext.Current.Server.MapPath("~/Uploads/"));
    if (strDirectories.Length > 0)
    {
        for (int count = 0; count < strDirectories.Length; count++)
        {
            string name = strDirectories[count].Substring(strDirectories[count].LastIndexOf("\\") + 1);
            if (name.Contains("_"))
            {
                string companyId = name.Substring(name.LastIndexOf("_") + 1);
                if (Convert.ToInt32(companyId) == OrgID)
                {
                    FolderName = name;
                    break;
                }
            }
        }
    }
    return FolderName;
}

此方法是通过线程池调用的,它在此行上给了我“对象引用未设置为对象的实例”的错误

string[] strDirectories = Directory.GetDirectories(HttpContext.Current.Server.MapPath("~/Uploads/"));

请帮帮我


解决方案

我用它HttpRuntime.AppDomainAppPath代替HttpContext.Current.Server.MapPath并且效果很好。

4

2 回答 2

2

HttpContext.Current返回执行线程中的当前上下文。线程池线程不负责任何 HTTP 请求,因此它没有上下文。该Current属性将返回 null,这就是您收到异常的原因。我建议你在转移到线程池Directory.GetDirectories() 之前调用。另一种方法是传递上下文。

EDIT: If you don't want to perform Directory.GetDirectories() in the thread pool thread, you could at least evaluate HttpContext.Current.Server.MapPath("~/Uploads/") in the original thread, and make that available to the thread pool. Basically you just want to avoid evaluating HttpContext.Current on the wrong thread.

于 2012-09-29T08:39:18.703 回答
1

HttpContext.Current.Server.MapPath("~/Uploads/")作为最后一个参数发送QueueUserWorkItem

于 2012-09-29T08:39:08.240 回答