這是一個相當惱人的問題,我無法在堆棧和谷歌搜索後進行數十次搜索。在asp.net web應用程序中獲取要讀取的文本文件的完整路徑
我有一個Asp.Net web應用程序,該解決方案本身有7個項目,其中之一是一個MVC項目,其中類如下所示的駐留。
using System;
using System.Web.Hosting;
namespace MyApp.Notifications
{
public class CustomEmails
{
private readonly string basePath = "C:\\Users\\MyUser\\MyAppName\\";
//HostingEnvironment.MapPath("~\\MyAppName")
//Server.MapPath("~")
//HostingEnvironment.ApplicationPhysicalPath("~");
//HostingEnvironment.ApplicationVirtualPath;
var subject = File.ReadAllText(basePath + "Notifications\\EmailTemplates\\EmailConfirmationEvent_Subject.txt");
//rest of classes code here
}
}
我可以讀取子文件夾中的文本文件的唯一方法是硬編碼路徑,如上所示。正如你上面看到的,我試圖以編程方式檢索應用程序的基本路徑,然後將其前置到文件子路徑。
正如你在上面看到的,在註釋掉的片段中,我嘗試了很多東西。
對於初學者來說,Server.MapPath永遠不會被允許,因爲它始終處於紅色狀態,intellisense不提供任何補救措施,並且使用Google搜索無法幫助其他人提供該Server.MapPath是IIS方法。所有其他代碼片段都不會返回任何內容。
我在做什麼錯?錯誤在哪裏?是不是有一種標準的方式來完成這個任務,因此無論您是在開發機器還是在主機虛擬機上,您總能獲得正確的基本路徑?
Per Darin的建議代碼更新如下;
public class EmailEvents
{
private static readonly string basePath = CustomEmails.GetWebsiteRoot();
public class EmailAddressVerified : IEventHandler<EmailVerifiedEvent<UserAccount>>
{
public void Handle(EmailVerifiedEvent<UserAccount> evt)
{
dynamic smtp = new SmtpMessageDelivery();
var localAppPath = CustomEmails.GetWebsiteRoot();
var htmlBody = CustomEmails.GetHtmlEmailMessage(DomainClasses.Enums.EmailType.AccountConfirmation);
//{ProductionChange} --change the first parameter to false in production
htmlBody = CustomEmails.FillEmailPlaceholderText(false, htmlBody, evt.Account);
htmlBody = htmlBody.Replace(CustomEmails.EmailTextPlaceholders.HtmlFileKey, EncryptDecrypt.EncryptQueryString(Guid.NewGuid().ToString()));
var subject = File.ReadAllText(Path.Combine(basePath, "Notifications", "EmailTemplates", "EmailConfirmationEvent_Subject.txt"));
subject = subject.Replace(CustomEmails.EmailTextPlaceholders.ApplicationName, CustomEmails.EmailPlaceholderValues.ApplicationName);
var msg = new Message { To = evt.Account.Email, Subject = subject, Body = htmlBody };
smtp.Send(msg);
}
}
}
在上面的示例中,basePath始終是空白,但localAppPath檢索正確的路徑。爲什麼類級別的專用變量不能檢索路徑?
確保您的項目引用了'System.Web'庫。之後,intellisense應該建議'使用System.Web.Hosting'爲你 –
我有,並仍然所有那些HostingEnvironment嘗試返回什麼 – dinotom
'HostingEnvironment.MapPath(「〜/」);''會給你網站根的絕對路徑。當然,這隻能在ASP.NET Web主機上運行。如果您嘗試在ASP.NET環境(例如單元測試)之外執行此代碼,則它顯然不會返回任何內容。 –