Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 it kept on throwing the error

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

Not sure where I made a mistake

like image 534
DoIt Avatar asked May 08 '14 14:05

DoIt


People also ask

Could not find a part of the path IIS Express?

If you have UAC turned off but are not running with elevated permissions, and try to write to restricted files (e.g. the "Program Files" folder) you'll get the "could not find a part of the path" error, instead of the (correct) access denied error.

Where are IIS Express files?

IIS Express uses a default, user-specific ApplicationHost. config file to allow many users to share the same computer without interfering with other user's settings. This file is located in the %userprofile%\Documents\IISExpress\config folder or %userprofile%\My Documents\IISExpress\config folder, depending on your OS.


2 Answers

You need to use HttpServerUtility.MapPath which will turn the ~/ portion of the path in to the real location it resildes on your hard drive.

So that would change your code to (assuming you are in one of the IIS classes that expose a Server property to it's methods)

var path = Server.MapPath(@"~/TextFiles/ActiveUsers.txt");

using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
{
    file.WriteLine(model.UserName.ToString());
}
like image 183
Scott Chamberlain Avatar answered Sep 24 '22 19:09

Scott Chamberlain


I ran into a similar issue and ended up using

string sFileName = HttpContext.Current.Server.MapPath(@"~/dirname/readme.txt");
like image 27
Chris Catignani Avatar answered Sep 25 '22 19:09

Chris Catignani