Server. MapPath (string sFilePath) reports that the object has not been referenced to the instance. server. mappath

Source: Internet
Author: User

Server. MapPath (string sFilePath) reports that the object has not been referenced to the instance. server. mappath

System. Web. HttpContext. Current. Server. MapPath (string sfilePath) converts a virtual path to a physical path. This must be called by Action in aspx or MVC, that is, it must have an HttpContext. Current object. But it seems that if System. Web. HttpContext. Current. Server. MapPath (string sfilePath) is called in the thread execution task, an exception is reported because there is no HttpContext. Current object.

System. AppDomain. CurrentDomain. BaseDirectory: application root path, which can be used when no HttpContext. Current object exists.

Before this problem occurs, use the Action in the Controller of MVC to call the System. web. httpContext. current. server. mapPath (string sfilePath) will cause an exception that "the object reference is not set to the instance of the object". Therefore, you must use System. appDomain. currentDomain. you can obtain the root path from BaseDirectory and then splice the desired file path and file name. // String sLogPath = System. web. httpContext. current. server. mapPath ("/Log/PaymentLog/AlipayLog/" + DateTime. now. toString ("yyyy-MM-dd") + ". txt "); string sLogPath = System. appDomain. currentDomain. baseDirectory. toString () + "/Log/PaymentLog/AlipayLog/" + DateTime. now. toString ("yyyy-MM-dd") + ". txt "; using (FileStream fileStream = new FileStream (sLogPath, FileMode. create, FileAccess. readWrite) {using (StreamWriter writer = new StreamWriter (fileStream) {// todo: business logic }}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.