3

I am trying to display contents of a text file in a view. So far I have been able to get the following code for the controller:

public ActionResult ShowFile()     
{         
     string filepath = Server.MapPath("\\some unc path\\TextFile1.txt");
     var stream = new StreamReader(filepath);         
     return File(stream.ReadToEnd(), "text/plain");      
} 

I do not know how to go ahead with the view.

Kindly advise.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Vipul
  • 107
  • 2
  • 4
  • 13

2 Answers2

8

Well, you could return Content instead, and it will render whatever you put in directly to the response stream, with the response type of text/plain.

Then you don't even need a View.

Also don't forget about disposing of your resources and exception handling. You don't want to put the stream.ReadToEnd() in the return call.

Do it like this:

[HttpGet]
public ActionResult ShowFile() {         
     string filepath = Server.MapPath("\\some unc path\\TextFile1.txt");
     string content = string.Empty;

     try {
        using (var stream = new StreamReader(filepath)) {
          content = stream.ReadToEnd();
        }
     }
     catch (Exception exc) {
       return Content("Uh oh!");
     } 

     return Content(content);
} 
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • Thanks for the advice but a code snippet would be more helpful. Also can you post code for file download...? – Vipul Aug 16 '11 at 05:57
  • Code snippet? What do you call the above then? Don't post the same comment in all answers, actually see if the comment is relevant to each one. – RPM1984 Aug 16 '11 at 06:00
  • 1
    And if you want file download, then use return File like what you have, and there IS no View, just a dialog to save the file. – RPM1984 Aug 16 '11 at 06:00
  • Got the content from the file. Thanks. – Vipul Aug 16 '11 at 09:31
0

Return Content(yourText) not a file result. That is for file downloads. If you want to set it in a view with other data as well then create a viewmodel class and assign your text to a property in the model.

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • i.e.: Razor View expects the following extensions: aspx, ascx, cshtml, and vbhtml. Can I add to these? – Idrees Dec 12 '11 at 16:43