Hi surbhik82,
I have created sample that full-fill your requirement by refering the below links.
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
}
table th
{
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th, table td
{
padding: 5px;
border-color: #ccc;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="File Name" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
C#
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;
public partial class CS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Id, Name FROM tblFiles WHERE Id IN(4,11,12)";
cmd.Connection = con;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
protected void View(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
try
{
ProcessRequest2(id, HttpContext.Current);
}
catch (SystemException ex)
{
Response.Write(ex.Message);
}
}
public void ProcessRequest2(int id, HttpContext context)
{
byte[] bytes;
string fileextension;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("@FileID", id);
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@FileID";
using (SqlDataReader sdr2 = cmd.ExecuteReader())
{
sdr2.Read();
bytes = (byte[])sdr2["Data"];
fileextension = sdr2["Name"].ToString();
}
con.Close();
}
}
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
if (fileextension.Substring(fileextension.IndexOf('.') + 1).ToLower() == "pdf")
{
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
else if (fileextension.Substring(fileextension.IndexOf('.') + 1).ToLower() == "doc" || fileextension.Substring(fileextension.IndexOf('.') + 1).ToLower() == "docx")
{
File.WriteAllBytes(Server.MapPath("~/Temp/" + fileextension), bytes);
WriteWordFile(Server.MapPath("~/Temp/" + fileextension));
}
}
private void WriteWordFile(object filePath)
{
object missingType = Type.Missing;
object readOnly = true;
object isVisible = false;
object documentFormat = 8;
string randomName = DateTime.Now.Ticks.ToString();
object htmlFilePath = Server.MapPath("~/Temp/") + randomName + ".htm";
string directoryPath = Server.MapPath("~/Temp/") + randomName + "_files";
ApplicationClass applicationclass = new ApplicationClass();
applicationclass.Documents.Open(ref filePath,
ref readOnly,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref isVisible,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType);
applicationclass.Visible = false;
Document document = applicationclass.ActiveDocument;
document.SaveAs(ref htmlFilePath, ref documentFormat, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType);
document.Close(ref missingType, ref missingType, ref missingType);
byte[] bytes;
using (FileStream fs = new FileStream(htmlFilePath.ToString(), FileMode.Open, FileAccess.Read))
{
BinaryReader reader = new BinaryReader(fs);
bytes = reader.ReadBytes((int)fs.Length);
fs.Close();
}
Response.BinaryWrite(bytes);
Response.Flush();
File.Delete(htmlFilePath.ToString());
foreach (string file in Directory.GetFiles(directoryPath))
{
File.Delete(file);
}
Directory.Delete(directoryPath);
if (File.Exists(filePath.ToString()))
{
File.Delete(filePath.ToString());
}
Response.End();
}
}
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports Microsoft.Office.Interop.Word
Partial Class VB
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Id, Name FROM tblFiles WHERE Id IN(4,11,12)"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub Upload(sender As Object, e As EventArgs)
Dim filename As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim contentType As String = FileUpload1.PostedFile.ContentType
Using fs As Stream = FileUpload1.PostedFile.InputStream
Using br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Long))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Dim query As String = "insert into tblFiles values (@Name, @ContentType, @Data)"
Using cmd As New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@ContentType", contentType)
cmd.Parameters.AddWithValue("@Data", bytes)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Protected Sub View(sender As Object, e As EventArgs)
Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
Try
ProcessRequest2(id, HttpContext.Current)
Catch ex As SystemException
Response.Write(ex.Message)
End Try
End Sub
Public Sub ProcessRequest2(id As Integer, context As HttpContext)
Dim bytes As Byte()
Dim fileextension As String
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("@FileID", id)
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@FileID"
Using sdr2 As SqlDataReader = cmd.ExecuteReader()
sdr2.Read()
bytes = DirectCast(sdr2("Data"), Byte())
fileextension = sdr2("Name").ToString()
End Using
con.Close()
End Using
End Using
context.Response.Buffer = True
context.Response.Charset = ""
context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
If fileextension.Substring(fileextension.IndexOf("."c) + 1).ToLower() = "pdf" Then
context.Response.Buffer = True
context.Response.Charset = ""
context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
context.Response.ContentType = "application/pdf"
context.Response.BinaryWrite(bytes)
context.Response.Flush()
context.Response.[End]()
ElseIf fileextension.Substring(fileextension.IndexOf("."c) + 1).ToLower() = "doc" OrElse fileextension.Substring(fileextension.IndexOf("."c) + 1).ToLower() = "docx" Then
File.WriteAllBytes(Server.MapPath(Convert.ToString("~/Temp/") & fileextension), bytes)
WriteWordFile(Server.MapPath(Convert.ToString("~/Temp/") & fileextension))
End If
End Sub
Private Sub WriteWordFile(filePath As Object)
Dim missingType As Object = Type.Missing
Dim [readOnly] As Object = True
Dim isVisible As Object = False
Dim documentFormat As Object = 8
Dim randomName As String = DateTime.Now.Ticks.ToString()
Dim htmlFilePath As Object = (Server.MapPath("~/Temp/") & randomName) + ".htm"
Dim directoryPath As String = (Server.MapPath("~/Temp/") & randomName) + "_files"
Dim applicationclass As New ApplicationClass()
applicationclass.Documents.Open(filePath, [readOnly], missingType, missingType, missingType, missingType, _
missingType, missingType, missingType, missingType, isVisible, missingType, _
missingType, missingType, missingType, missingType)
applicationclass.Visible = False
Dim document As Document = applicationclass.ActiveDocument
document.SaveAs(htmlFilePath, documentFormat, missingType, missingType, missingType, missingType, _
missingType, missingType, missingType, missingType, missingType, missingType, _
missingType, missingType, missingType, missingType)
document.Close(missingType, missingType, missingType)
Dim bytes As Byte()
Using fs As New FileStream(htmlFilePath.ToString(), FileMode.Open, FileAccess.Read)
Dim reader As New BinaryReader(fs)
bytes = reader.ReadBytes(CInt(fs.Length))
fs.Close()
End Using
Response.BinaryWrite(bytes)
Response.Flush()
File.Delete(htmlFilePath.ToString())
For Each file_1 As String In Directory.GetFiles(directoryPath)
File.Delete(file_1)
Next
Directory.Delete(directoryPath)
If File.Exists(filePath.ToString()) Then
File.Delete(filePath.ToString())
End If
Response.[End]()
End Sub
End Class
Database
Screenshot