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

后端 未结 4 2271
悲哀的现实
悲哀的现实 2021-02-19 10:07

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 Sys         


        
相关标签:
4条回答
  • 2021-02-19 10:46

    This is an old question but I just ran into this problem myself and wanted to add what I've just discovered, in case it's helpful to anyone else.

    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.

    To eliminate the problem, run with elevated permissions as in this solution: https://stackoverflow.com/a/1885543/3838199

    0 讨论(0)
  • 2021-02-19 11:03

    I ran into a similar issue and ended up using

    string sFileName = HttpContext.Current.Server.MapPath(@"~/dirname/readme.txt");
    
    0 讨论(0)
  • 2021-02-19 11:03

    ~ is not the "user home" or anything else in Windows. You can still set the path as relative to the working directory (where the executable is) by just not specifying a full path.

    0 讨论(0)
  • 2021-02-19 11:06

    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());
    }
    
    0 讨论(0)
提交回复
热议问题