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では実行時のカレントディレクトリは
になります。
Windows Server 2008, Windows Server 2012などのIISがインストールされているOSでは実行時のカレントディレクトリは
になります。
カレントディレクトリが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();
}
}
}
}