Reputation: 317
I'm developing a website using ASP.NET MVC. I've multiline Data which I'm storing in a text line and saved that text file in ContentData Folder in my application. I'm hitting the error that file path is not found like this
Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\ContentData\WTE.txt'
Please Look at my code and help me how to do this.
This is the View:
@{
ViewBag.Title = "WhatToExpect";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<h2></h2>
@{
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new
System.IO.StreamReader(@"~/ContentData/WTE.txt");
while((line = file.ReadLine()) != null)
{
string notes= line;
Html.Raw(notes);
counter++;
}
<div id="ChurchImage">
<img src="../../Images1/redeemer.jpg" alt="" />
</div>
file.Close();
}
I've tried replacing @ in the file path. Nothing worked.Please Help me out.Thanks in advance
Upvotes: 2
Views: 2895
Reputation: 4208
// Get your root directoty
var root = AppDomain.CurrentDomain.BaseDirectory;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader( root + @"/ContentData/WTE.txt");
Edit
Your controller should be like,
public ActionResult Index()
{
var root = AppDomain.CurrentDomain.BaseDirectory;
string line;
System.IO.StreamReader file = new System.IO.StreamReader( root + @"/Content/Site.css");
var fileLines = new List<string>();
while ((line = file.ReadLine()) != null)
{
fileLines.Add(line);
}
// You can use model, temdata or viewbag to carry your data to view.
ViewBag.File = fileLines;
return View();
}
And now you can use this ViewBag.File
in your view to render your file data.
@{
string line;
foreach (var item in ViewBag.File)
{
<p>@item</p>
}
}
Upvotes: 3
Reputation: 11
Add server mappath to your path.
System.IO.StreamReader(@Server.MapPath("~/ContentData/WTE.txt"));
Upvotes: 1