Could not find part of path 'C: \ Program Files (x86) \ IIS Express \ ~ \ TextFiles \ ActiveUsers.txt'

I tried many ways to access a text file in my Visual Studio 2012 solution from a folder named TextFiles

 using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"~/TextFiles/ActiveUsers.txt", true)) { file.WriteLine(model.UserName.ToString()); } 

But he kept throwing a mistake

Could not find part of path 'C: \ Program Files (x86) \ IIS Express \ ~ \ TextFiles \ ActiveUsers.txt ".

I don’t know where I made a mistake.

+9
c #
source share
4 answers

You need to use HttpServerUtility.MapPath , which will turn part of the ~/ path to the real location that it rebuilds on the hard drive.

So, this will change your code (if you are in one of the IIS classes that expose the Server property for it)

 var path = Server.MapPath(@"~/TextFiles/ActiveUsers.txt"); using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true)) { file.WriteLine(model.UserName.ToString()); } 
+12
source share

This is an old question, but I just ran into this problem and wanted to add what I just opened, in case this helps someone else.

If UAC is turned off but does not work with increased permissions and tries to write files with limited access (for example, to the "Program Files" folder), you will receive the message "could not find part of the path", instead of (correct) denial of access.

To fix the problem, run with elevated permissions, as in this solution: https://stackoverflow.com/a/316626/

+1
source share

~ not a "home user" or anything else on Windows. You can still set the path relative to the working directory (where the executable is), simply without specifying the full path.

0
source share

I ran into a similar problem and ended up using

 string sFileName = HttpContext.Current.Server.MapPath(@"~/dirname/readme.txt"); 
0
source share

All Articles