2012-01-27 101 views
6

我试图打开包含在我的C#是运行Web目录中的一些数据文件的文件中的所有文本。基本上只是把它变成一个字符串。我试着做以下...ASP .NET C#得到在网络路径

string email = File.ReadAllText("/orderforms/email_templates/file_to_include.txt"); 

我不知道这是正确的方法,但它似乎有一个寻路的问题,整个路径将根据它运行在什么样的Web服务器更改。

这是在目录设置...

/Classes/Page.ascx.cs (the page that tries to read the text from the 
file) 
/orderforms/<one of multiple pages execute the above class here or in a sub directory 
/orderforms/email_templates/file_to_include.txt 
/orderforms/email_templates/file_to_include2.txt 

我应该使用什么路径和功能上的所有文件的内容读取到一个字符串?

感谢

+1

仅供参考,每当一个URL路径以斜杠开头( “/” ),它被应用程序解释为网站ROOT,这意味着它被放置在域名后面以构建完整的URL。这与app-root不同,由asp.net应用程序(服务器端)中的“〜”字符表示。通常,app-root与site-root相同(当没有涉及虚拟目录时),但在开发环境中,通常也包含虚拟目录(使用本地IIS时),因此您必须小心与领先的斜线。 – 2012-01-27 16:03:06

+0

我以前的评论与你的问题没有直接关系,但我有一种感觉,你需要知道我说的是什么。 – 2012-01-27 16:04:12

回答

24

试试这个:

string email = File.ReadAllText(Server.MapPath("~/orderforms/email_templates/file_to_include.txt")) 
+3

你必须有HttpContext来做到这一点,做到这一点,我不得不补充说。 'string email = File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(“〜/ orderforms/email_templates/file_to_include.txt”));' – ferics2 2012-12-17 22:00:05