Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET C# get all text from a file in the web path

Tags:

c#

.net

asp.net

I'm trying to open a file that includes some data in a web directory that my C# is running. Basically just turns it into a string. I tried doing the following...

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

I'm not sure if that is the correct method, but it seems there is a pathing problem, the whole path will change depending what web server it is running on.

This is the directory setup...

/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

What path and function should I use to read all of the contents of the file to a string?

Thanks

like image 228
TheFrack Avatar asked Jan 27 '12 15:01

TheFrack


2 Answers

Try this:

string email = File.ReadAllText(Server.MapPath("~/orderforms/email_templates/file_to_include.txt"))
like image 198
Jeremy Armstrong Avatar answered Sep 25 '22 06:09

Jeremy Armstrong


You need to use Server.MapPath:

http://msdn.microsoft.com/en-us/library/ie/ms524632(v=vs.90).aspx

like image 38
mbx-mbx Avatar answered Sep 25 '22 06:09

mbx-mbx