24

I am trying to construct a file path in order to read an XSLT file, like so:

string path = "../_xslt/example.xslt";
StreamReader reader = new StreamReader(path); 

...where I am in a controller (/Controllers/ExampleController.cs), and the '/_xslt/' folder is at the same level as '/Controllers'

However, the error I am getting is:

(System.IO.DirectoryNotFoundException) Could not find a part of the path 'c:\windows\system32\_xslt\example.xslt'.

Am I going about this the wrong way?

Thanks for any help!

3 Answers 3

35

You can use the HttpServerUtility.MapPath method to map any relative paths for you, in your controller this is easily accessible via the ControllerContext:

string path = ControllerContext.HttpContext.Server.MapPath("~/_xslt/example.xslt");
...
Sign up to request clarification or add additional context in comments.

Comments

6
string TestX()
{
    string path = AppDomain.CurrentDomain.BaseDirectory; // You get main rott
    string dirc = ""; // just var for use
    string[] pathes = Directory.GetDirectories(path); // get collection

    foreach (string str in pathes)
    {
        if (str.Contains("NameYRDirectory")) // paste yr directory
        {
            dirc = str;
        }
    }

    return dirc; // after use Method and modify as you like
}

Comments

4

If controller is present at directory root

String path = ControllerContext.HttpContext.Server.MapPath(@"~/_xslt/example.xslt");

Else

String path = ControllerContext.HttpContext.Server.MapPath(@"../_xslt/example.xslt");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.