How to dynamically grab the Content folder directory?

Asked

Viewed 499 times

1

My question is the same as the title: how to create a variable that points to the Content folder?

I have a file there and I want to access it. I tried so but unsuccessfully:

StreamReader file =
new StreamReader(@"~/Content/tb_ocupacao.txt", Encoding.GetEncoding("iso-8859-1"));

1 answer

4


Use Server.MapPath

If you’re going to use the code on a controller

var caminho = Server.MapPath("~/Content");
var file = new StreamReader($"{caminho}/tb_ocupacao.txt", 
                              Encoding.GetEncoding("iso-8859-1"));

If you’re gonna use it outside

var caminho = System.Web.HttpContext.Current.Server.MapPath("~/Content");
var file = new StreamReader($"{caminho}/tb_ocupacao.txt", 
                              Encoding.GetEncoding("iso-8859-1"));
  • Which library I have to import to recognize Server?

  • 2

    None. That’s from namespace System.Web.

  • I want to use this code in a class, I’m already using the System.Web, even so Server is not being recognized. Some other tip?

  • This code needs to be in a request

  • 2

    @Italorodrigo you should have specified this in your question, if you can use it like this: System.Web.HttpContext.Current.Server.MapPath

  • 1

    @Virgilionovic worked, thanks. Sorry if I didn’t specify well, I’m still learning MVC.

  • @Virgilionovic will post an answer? Because if not, I will edit mine to not be incomplete.

  • @LINQ can use the comment without problems! vlw

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.