Link to home
Start Free TrialLog in
Avatar of madkrell
madkrell

asked on

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

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.
SOLUTION
Avatar of devlab2012
devlab2012
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of madkrell
madkrell

ASKER

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.