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 }}