LoginSignup
7
7

More than 5 years have passed since last update.

ASP.NETのルートフォルダの物理パスの取得について。Request.PhysicalApplicationPathはApplication_Start内で使用できないのでMapPathを使う

Last updated at Posted at 2016-02-25

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でした。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7