ASP.NETでローカルパスでファイルを指定したにもかかわらず、ファイルが見つからない旨のエラーが発生することがあります。
エラーが発生するコード
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace iPentecWebSearch
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FileStream fs = new FileStream("data.txt", FileMode.Open, FileAccess.Read);
try {
StreamReader sr = new StreamReader(fs);
string text = sr.ReadToEnd();
Literal_SearchTag.Text = text;
sr.Close();
}
finally {
fs.Close();
}
}
}
}
上記のコードを実行してもファイルが無い旨のエラーが表示されます。
原因
ASP.NETではWebアプリケーションの実行時のカレントディレクトリはIISのプログラムフォルダになります。
Windows7, Windows8など、IIS Express がインストールされているクライアントOSでは実行時のカレントディレクトリは
C:\Program Files (x86)\IIS Express
になります。
Windows Server 2008, Windows Server 2012などのIISがインストールされているOSでは実行時のカレントディレクトリは
c:\windows\system32\inetsrv
になります。
対策
カレントディレクトリがIISのプログラムディレクトリのため、aspxファイルを配置したディレクトリのファイルを開く場合には明示的にファイルを配置してあるディレクトリのパスを与えます。
ASP.NETでは"Request.PhysicalApplicationPath"により、アプリケーションのルートディレクトリの物理パスを取得できますので、これを用います。
コード例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace iPentecWebSearch
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FileStream fs = new FileStream(
Request.PhysicalApplicationPath + "data.txt", FileMode.Open, FileAccess.Read);
try {
StreamReader sr = new StreamReader(fs);
string text = sr.ReadToEnd();
Literal_SearchTag.Text = text;
sr.Close();
}
finally {
fs.Close();
}
}
}
}
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2013-08-19