Recently I started working with ASP.NET. So, I have an MVC site (a little different from the original template). I want to see the text from the file when I open the Home / About page ... Well, then you probably understand: I naively began to use StreamReader. As a result, our “favorite” FileNotFoundException . I have already tried different options: insert the code in cshtml using Razor, put the code in HomeController.cs . In general, please explain why the StreamReader does not work, why it does not find the file and how to fix it ... Oh yes! I do not know the full path)

 string text; StreamReader sr = new StreamReader("TextFile1.txt") text = sr.ReadLine(); ViewBag.Message = text; 

PS File placed in the folder with the code and in the folder of the project

  • The absolute path tried to ask? - free_ze
  • because you need to specify the full path to the file, and not just the name. When specifying the name, the server will search for it in the current directory, working directory, and so on in order. - teran
  • Throw it in the bin folder, and you will most likely be happy, but it is more logical in bin\add_data - teran

2 answers 2

 string appDataPath = System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data"); string fileName = "TextFile1.txt"; string absolutePathToFile = Path.Combine(appDataPath, fileName); StreamReader sr = new StreamReader(absolutePathToFile) ; ... 

A source

  • It all worked! And you gave me cool advice not only on ASP.NET - Mr. Don't know

I hope this helps you.

Read Data From XML in ASP.Net MVC 5 http://www.c-sharpcorner.com/UploadFile/xiankaylle/read-data-from-xml-in-Asp-Net-mvc-5/

  • Partially you answered my previous question, but did not answer this. Can you more accurately explain? - Mr. Don't know