【问题标题】:Object reference not set to an instance of an object?你调用的对象是空的?
【发布时间】:2009-05-19 22:03:44
【问题描述】:

我写了这些行,但我有 NullReferenceException。请帮我解决它!

string FullPath = TempPath + FileName;
System.Drawing.Image Adimg = null;
Adimg = System.Drawing.Image.FromFile(MapPath(FullPath));

我将这些行放在 Public bool 方法中,TempPath 是类属性,FileName 是该方法的输入。

exception Detail:
System.NullReferenceException was unhandled by user code
  Message="Object reference not set to an instance of an object."
  Source="System.Web"
  StackTrace:
       at System.Web.UI.Page.MapPath(String virtualPath)
       at FileIO.HasValidAttributes(String FileName) in g:\MyProjects\ASP.net Projects\ADBridge\adengine2\App_Code\FileIO.cs:line 44
       at UploadPage.<Page_Load>b__0(Object sender1, EventArgs e1) in g:\MyProjects\ASP.net Projects\ADBridge\adengine2\UploadPage.aspx.cs:line 29
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 


我没有时间!

【问题讨论】:

  • 那么 - 你的临时路径和文件名是什么?从堆栈跟踪中可以看出问题所在

标签: c# file file-io filesystems


【解决方案1】:

尝试在 Server 对象上调用 MapPath:

HttpContext.Current.Server.MapPath(FullPath)

【讨论】:

    【解决方案2】:

    这里有一些提示:

    1. 使用 Path.Combine 从各个部分构建路径
    2. 验证 FullPath 引用的文件是
      • 存在于磁盘上
      • 可由 Web 进程读取(即不在系统帐户或类似帐户下运行 Web 进程)

    【讨论】:

    • 字符串 FullPath = Path.Combine(TempPath, FileName);但不工作。问题依旧存在!请注意我的文件是 Peresent 在磁盘上。
    • 字符串 FullPath = Path.Combine(TempPath, FileName);但不工作。问题依旧存在!请注意我的文件是 Peresent 在磁盘上。
    • 您是否检查了 Web 服务用户有权访问该文件的其他内容?
    【解决方案3】:

    读取“Fullpath = TempPath + FileName”,您似乎正在尝试将物理地址作为虚拟地址传递?

    是这样吗?如果不是,你能给我们你传入的作为这个函数的输入吗?如果是物理路径,则不需要使用 MapPath。

    here

    【讨论】:

    • 我的 TempPath:私有字符串 _TempPath = "~/Images/";公共字符串 TempPath { 获取 { 返回 _TempPath; } 设置 { _TempPath = 值; } } 我的文件名:“imdb.png”
    【解决方案4】:

    试试这个:

    string fullPath = Path.Combine(TempPath, FileName);
    System.Drawing.Image adimg = null;
    if (!String.IsNullOrEmpty(fullPath))
    {
        string serverPath = HttpContext.Current.Server.MapPath(fullPath);
        if (!String.IsNullOrEmpty(serverPath))
            adimg = System.Drawing.Image.FromFile(serverPath);
    }
    

    确保MapPath 提供您所期望的。

    【讨论】:

      猜你喜欢
      • 2013-05-27
      • 2013-07-22
      相关资源
      最近更新 更多