Read fileupload control file content in Asp.Net

InfoPath alternatives for form designing SharePoint

In this post we will discuss about how to read content from a file in fileupload control directly without saving anywhere in the server. Also you can check out my previous posts on:

– Tutorial on MVVM with WPF

– ABC of WCF

– Working with enterprise library for data access in asp.net Part-3

Below is the full code to read fileupload control file content in Asp.Net:

.aspx code:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”ReadFileContent.aspx.cs”
Inherits=”ReadFileContent” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Read fileupload control file content in Asp.Net</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:FileUpload ID=”fuUploadFile” runat=”server” /><br />
<asp:Button ID=”btnReadContent” runat=”server” Text=”Read Content” OnClick=”btnReadContent_Click” /><br />
<asp:Label ID=”lblFileContent” runat=”server” Text=””></asp:Label>
</div>
</form>
</body>
</html>


.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class ReadFileContent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnReadContent_Click(object sender, EventArgs e)
{
if (fuUploadFile.HasFile)
{
if (fuUploadFile.PostedFile.ContentLength > 0)
{
string fullContent = string.Empty;
Stream objStream;
Int32 intFileLength = fuUploadFile.PostedFile.ContentLength;

// Create a byte array to hold the contents of the file.
Byte[] Input = new Byte[intFileLength];

// Initialize the stream to read the uploaded file.
objStream = fuUploadFile.FileContent;

// Read the file into the byte array.
objStream.Read(Input, 0, intFileLength);

UTF8Encoding encoding = new UTF8Encoding();
fullContent = encoding.GetString(Input);

lblFileContent.Text = fullContent;
}
}
}
}

The output will come as shown in the figure below:

 

Similar SharePoint 2013 Tutorials


About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →

Leave a Reply