In this article i will show you how you can read or extract or Get a text file content content in your asp.net core 6 or mvc application using c#.net. So for this article we will place a text file having some text in file in wwwroot folder and then we will read the content of test file.
Other related articles: Upload Multiple File To wwwroot Folder in ASP.NET Core Using C#.Net, Asp.net Core 6 Multiple File Upload, How To Upload Multiple File Asp.net core 6, Display Data In Table/Tabular Format In Asp Net Core 6/MVC Using C#.Net (Ms Sql Database), Search And Display Data In Table/Tabular Format in Asp.net Core 6/MVC using C# (Ms Sql Server).
Now for this article first we will create a new asp.net core 6 application and add text file wwwroot folder.
Now add some content into it.
Now in your controller or class file add the below code. This piece of core will make you enable to read the passed text file present into your wwwroot folder.
public string ReadTextFile(string
filepath) { var buildDir =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var filePath = Path.Combine(buildDir, filepath); return System.IO.File.ReadAllText(filePath); } |
Now before moving further we we need make some changes into the property of wwwroot added text file. So for making changes in Text file property we will Right Click -> Properties. Now in property window we will set Copy to Output Directory as Copy if newer.
Note: If you don't make the above setting in your file property your code will throw exception.
Now we will write the code to read and display the text file content in your view. So for reading the content we will call the written method on controller.
[HttpGet] public
IActionResult Index() { string textfilevalue = ReadTextFile("TextFile.txt"); ViewBag.Data = textfilevalue; return View(); } |
In above code i have read the text file content and then pass it to ViewBag to display text file data on view page. Now run the code and check the output.
0 comments:
Please let me know your view