ASP.NETのルートの物理パスを取得するには
private void MyMethod1()
{
String rootPath = context.Request.PhysicalApplicationPath;
}
しかしアプリケーションの開始時に取得しようとするとエラーになります。(※IIS7 Integrated modeの場合)
これはApplication_Startの時点ではRequestオブジェクトがまだセットアップされていないのが理由です。
void Application_Start(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
String appPath = context.Request.ApplicationPath;//RequestプロパティがNullで例外発生
}
アプリケーションの初期化時にルートフォルダのパスがほしい場合などには困ります。
例)GoogleBigQueryを使用する場合は認証用のMyCert.p12ファイルが必要。アプリケーションの開始時に読み込んでおきたい。
ということでそういう場合はHttpContext.Current.Server.MapPath("~/")を使用しましょう。これでルートフォルダの物理パスが取得できます。
void Application_Start(object sender, EventArgs e)
{
var certificateFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/"), "MyCert1.p12");
}
以上Tipsでした。