【问题标题】:Error while reading a text file in asp.net MVC在 asp.net MVC 中读取文本文件时出错
【发布时间】:2016-01-01 23:33:25
【问题描述】:

我正在使用 ASP.NET MVC 开发一个网站。我将多行数据存储在文本行中,并将该文本文件保存在应用程序的 ContentData 文件夹中。 我遇到了这样的错误,即找不到文件路径

找不到路径“C:\Program Files (x86)\IIS”的一部分 快递\~\ContentData\WTE.txt'

请查看我的代码并帮助我执行此操作。

这是视图:

 @{
    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();
    }

我尝试替换文件路径中的@。没有任何效果。请帮助我 out.提前谢谢

【问题讨论】:

  • 实际路径是什么?
  • 我已将文本文件放在名为 ContentData 的文件夹中。该文件夹是我的应用程序中的文件夹之一。实际路径是“~/ContentData/WTE.txt”
  • 尝试使用System.IO.StreamReader(HttpContext.Server.MapPath("~/ContentData/WTE.txt")); 并确保文件存在。
  • 它工作#Waqar Ahmed..谢谢你。但我只能显示图像。请查看我的代码并告诉我如何显示文本?
  • 我想显示文本文件中的数据。哪个 HTML 助手适合这个?

标签: c# asp.net-mvc visual-studio streamreader


【解决方案1】:
// 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");

编辑

你的控制器应该是这样的,

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();
}

现在您可以在视图中使用此ViewBag.File 来呈现您的文件数据。

@{
    string line;
    foreach (var item in ViewBag.File)
    {
        <p>@item</p>
    }
}

【讨论】:

  • 我想显示文本文件中的数据。哪个 HTML 助手适合这个?
  • @sujaykodamala,您的数据的性质是什么?您希望如何在您的应用程序中使用这些数据?我的意思是只显示每一行还是要提取每个单词或某些东西来做任何逻辑?
  • 我只想显示文本文件中的数据。这对@Abishek 有帮助吗?
  • 这是一个多行文本。
  • @sujaykodamala,我认为您已经在代码中完成了此操作。正确的?通过使用“while”循环。
【解决方案2】:

将服务器映射路径添加到您的路径。

System.IO.StreamReader(@Server.MapPath("~/ContentData/WTE.txt"));

【讨论】:

  • 我想显示文本文件中的数据。哪个 HTML 助手适合这个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 2013-09-26
相关资源
最近更新 更多