How to stream text documents using MVC4.0?


Do you wanted to learn stream functionality in ASP.NET MVC 4.0. This article will help you to understand stream functionality in MVC 4.0. In this article I have used WEB API to explain this feature.

If you are new to MVC4.0 then this article will help you in understanding stream functionality. ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. Mostly Web-Api is expressed in JSON or XML. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.


using yournamespacename.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Data;
using System.Data.OleDb;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
//Add required namespaces here. Remove unwanted namespaces.


namespace yournamespacename.Controllers
{
public class controllername: ApiController
{
HttpResponseMessage my_response = new HttpResponseMessage();
public HttpResponseMessage Get(string path_Of_file)
{
try
{
var fs = new FileStream(path_Of_file, FileMode.Open);
var fn = Path.GetFileName(path_Of_file);
var result_val = new MultipartFormDataContent();
result_val.Add(new StreamContent(fs), "contents", fn);
my_response.Content = new StreamContent(fs);
my_response.StatusCode = HttpStatusCode.OK;
return my_response;
}
catch (IOException)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error is encountered!");
}
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error is encountered!");
}


I have added ApiController as I am using WEB-API here. You can test above code with the help of any web debugging tool such as fiddler.
You have to use .txt file for streaming. You will see the contents of the file as a output.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: