Generate HTML file and save in Database as Binary using C# and VB.Net in ASP.Net

Last Reply 8 months ago By pandeyism

Posted 8 months ago

Hi

i m generating an html file. i need to convert it to binary and update in the database.

new html file will be cretated from a function. i will attach the function.

@vcFilepath in the above code is binary coloumn in database.i need to update that coloumn.

public string FetchAllBookmarkForFile(String UserId)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString);
    string newFileName = string.Empty;
    txtDownload.Text = tvBookContent.SelectedValue;
    //string Filepath = hdnCurrentFilePath.Value;
    if (!string.IsNullOrEmpty(Session["UserId"].ToString()))
    {
        BookTree obj = new BookTree();
        DataSet dsBookmark = obj.FetchAllBookmarkForFile(Session["UserId"].ToString());
        if (dsBookmark != null)
        {
            for (int i = 0; i < dsBookmark.Tables[0].Rows.Count; i++)
            {
                string fileContents = hdnCurrentFilePath.Value;
                // string fileContents = (Server.MapPath("~/File/htmlFile") + newFileName);
                //string fileContents =(string.IsNullOrEmpty(newFileName) ? FilePath : "\\UserFiles\\" + newFileName);
                string searchText = HttpUtility.HtmlEncode(dsBookmark.Tables[0].Rows[i]["BookmarkLineText"].ToString());
                string newBookmarktag = "<font><b><a name='" + dsBookmark.Tables[0].Rows[i]["BookmarkName"].ToString() + "'>" + dsBookmark.Tables[0].Rows[i]["BookmarkLineText"].ToString() + "</a></b></font>";
                if (fileContents.IndexOf(searchText) < 0)
                {
                    //Find out text
                    //breakdown text
                    string[] brokenSearchText = searchText.Split(' ');
                    int previousIndex = 0;
                    //Create pattern
                    ArrayList htmltextIndex = new ArrayList();
                    Match matchhtml = null;
                    for (int j = 0; j < brokenSearchText.Length; j++)
                    {
                        if (!string.IsNullOrEmpty(brokenSearchText[j]))
                        {
                            matchhtml = Regex.Match(fileContents, brokenSearchText[j] + @".*");
                            break;
                        }
                        else
                        {
                            previousIndex++;
                        }
                    }
                    while (matchhtml.Success)
                    {
                        htmltextIndex.Add(matchhtml.Index);
                        matchhtml = matchhtml.NextMatch();
                    }
                    bool ismatched = false;

                    foreach (Int32 index in htmltextIndex)
                    {
                        string htmlsubstring = fileContents.Substring(index - previousIndex, searchText.Length);
                        int match = 0;
                        for (int j = 0; j < brokenSearchText.Length; j++)
                        {
                            if (htmlsubstring.Contains(brokenSearchText[j]))
                            {
                                match++;
                            }
                        }
                        if (match >= (brokenSearchText.Length / 2))
                        {
                            ismatched = true;
                            int increaseindex = 0;
                            increaseindex = increaseindex + htmlsubstring.Split(new[] { "\r" }, StringSplitOptions.RemoveEmptyEntries).Length - 1;
                            increaseindex = increaseindex + htmlsubstring.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).Length - 1;
                            if (increaseindex > 0)
                            {
                                increaseindex = increaseindex + increaseindex / 2;
                            }
                            string newhtmlsubstring = fileContents.Substring(index - previousIndex, searchText.Length + increaseindex);
                            //searchText = htmlsubstring;
                            searchText = newhtmlsubstring;
                            break;
                        }
                        else
                        {
                            ismatched = false;
                        }
                    }
                    // fileContents = fileContents.Replace(searchText, newBookmarktag);
                    // ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Bookmark Not Found');", true);
                }
                else
                {
                    fileContents = fileContents.Replace(dsBookmark.Tables[0].Rows[i]["BookmarkLineText"].ToString(), newBookmarktag);
                }
                newFileName = (string.IsNullOrEmpty(newFileName) ? DateTime.Now.Ticks.ToString() + ".htm" : newFileName);
                //newFileName = (string.IsNullOrEmpty(newFileName) ? hdnCurrentFilePath.Value.Replace("htmlFile", "").Replace("\\", "").Replace(".htm", "") + "_" + Session["UserId"].ToString() + ".htm" : newFileName);
                //byte[] data = File.ReadAllBytes(newFileName);
                // byte[] data = newFileName;
                byte[] data = File.ReadAllBytes(Server.MapPath("~/File/newFileName.htm"));
                //System.IO.File.WriteAllText(HttpContext.Current.Server.MapPath("~/UserFiles/") + newFileName, fileContents);
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_updatebrkm";
                cmd.Parameters.AddWithValue("@vcFilePath", data);
                cmd.Parameters.AddWithValue("@iModuleId", txtDownload.Text);
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
    return newFileName;
}

 

Posted 8 months ago Modified on 8 months ago

Hi suhaas121,

Take reference to below code and change your code.

HTML

<asp:Button Text="Update" runat="server" OnClick="Update" />

Namespaces

C#

using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

VB.Net

Imports System.IO
Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Update(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country", typeof(string)) });
    dt.Rows.Add(1, "John Hammond", "United States");
    dt.Rows.Add(2, "Mudassar Khan", "India");
    dt.Rows.Add(3, "Suzanne Mathews", "France");
    dt.Rows.Add(4, "Robert Schidner", "Russia");
    StringBuilder sb = new StringBuilder();
    sb.Append("<table border='1'>");
    sb.Append("<tr>");
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append("<td>" + dt.Columns[i].ColumnName + "</td>");
    }
    sb.Append("</tr>");
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        sb.Append("<tr>");
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            sb.Append("<td>" + dt.Rows[i][j] + "</td>");
        }
        sb.Append("</tr>");
    }
    sb.Append("</table>");
    string fileName = DateTime.Now.Ticks.ToString() + ".htm";
    File.WriteAllText(Server.MapPath("~/Files/" + fileName), sb.ToString());
    byte[] data = File.ReadAllBytes(Server.MapPath("~/Files/" + fileName));
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection())
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_updatebrkm";
            cmd.Parameters.AddWithValue("@Data", data);
            cmd.Parameters.AddWithValue("@Id", "1");
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

VB.Net

Protected Sub Update(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
    dt.Rows.Add(1, "John Hammond", "United States")
    dt.Rows.Add(2, "Mudassar Khan", "India")
    dt.Rows.Add(3, "Suzanne Mathews", "France")
    dt.Rows.Add(4, "Robert Schidner", "Russia")
    Dim sb As StringBuilder = New StringBuilder()
    sb.Append("<table border='1'>")
    sb.Append("<tr>")
    For i As Integer = 0 To dt.Columns.Count - 1
        sb.Append("<td>" & dt.Columns(i).ColumnName & "</td>")
    Next
    sb.Append("</tr>")
    For i As Integer = 0 To dt.Rows.Count - 1
        sb.Append("<tr>")
        For j As Integer = 0 To dt.Columns.Count - 1
            sb.Append("<td>" & dt.Rows(i)(j) & "</td>")
        Next
        sb.Append("</tr>")
    Next
    sb.Append("</table>")
    Dim fileName As String = DateTime.Now.Ticks.ToString() & ".htm"
    File.WriteAllText(Server.MapPath("~/Files/" & fileName), sb.ToString())
    Dim data As Byte() = File.ReadAllBytes(Server.MapPath("~/Files/" & fileName))
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection()
        Using cmd As SqlCommand = New SqlCommand()
            cmd.Connection = con
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "sp_updatebrkm"
            cmd.Parameters.AddWithValue("@Data", data)
            cmd.Parameters.AddWithValue("@Id", "1")
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
End Sub