~ c# path to text file not using root of application

madkrell used Ask the Experts™
Hi experts,

A problem with trying to use a relative path to a text file is driving me crazy as it appears to want to goto the root of the dev server or IIS server C:/ instead of the application root.  I have tried using all of the following options to point to the correct file but none seem to work:

Label1.Text = System.IO.File.ReadAllText(Request.ApplicationPath.TrimEnd('/') +"/Standard/TextFile1.txt", System.Text.Encoding.Default);  

Label1.Text = System.IO.File.ReadAllText("~/Standard/TextFile1.txt", System.Text.Encoding.Default);    

Label1.Text = System.IO.File.ReadAllText("../Standard/TextFile1.txt", System.Text.Encoding.Default);  

Label1.Text = System.IO.File.ReadAllText(Path.Combine(Environment.CurrentDirectory, @"..\..\TextFile1.txt"), System.Text.Encoding.Default);          

Label1.Text = System.IO.File.ReadAllText(Page.ResolveUrl("~/Standard/TextFile1.txt"), System.Text.Encoding.Default);  
The absolute path to the text tile is actually = C:/Users/Administrator/Documents/Visual Studio 2010/Projects/SupplierPortal/SupplierPortal/textfiles/TextFile1.txt

However it is reading the root path as below and I get this error:

System.IO.DirectoryNotFoundException was unhandled by user code
  Message=Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\Standard\TextFile1.txt'.

Can anyone please help me understand how I fix this?   I need to use relative paths because evenntually the web app will be deployed to another server.

Has it got anything to do with using it with the System.IO statement?  I use relative paths in the rest of my application by using '~' to images all ok from both code behind and in CSS file so I cannot understand why this is happening?
Thanks in advance.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Use Server.MapPath() function
           string path = Server.MapPath("Standard\TextFile1.txt");


Perffect, thanks AlfredRobot !!

I had tried to use Server.MapPath() previously but obviously had some of the syntax incorrect so thanks for providing the actual code I need to solve this.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial