【问题标题】:How to add file content to Viewbag mvc4如何将文件内容添加到 Viewbag mvc4
【发布时间】:2014-10-14 10:05:52
【问题描述】:

是否可以将 txt 文件的内容添加到控制器内的 Viewbag 中?怎么做?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    是的,这是可能的。您只需要 read file contents to a string 并将该值传递给 Viewbag。

    类似的东西可以工作:

    ViewBag.FileText = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
    

    【讨论】:

    • 谢谢,这可行,但是否可以指向项目内部的文件形式,例如。 ~/Views/file.txt ?
    • 不客气!试试 HttpContext.Current.Server.MapPath("~/Views/file.txt");
    【解决方案2】:

    例如,您可以通过将文件读入字符串并将其传递到 ViewBag 中来实现。

    string fileContent = System.IO.File.ReadAllText("C:/path/file.txt");
    ViewBag.Whatever = fileContent;
    

    【讨论】:

      猜你喜欢
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      相关资源
      最近更新 更多