Monday, March 26, 2012

Read Text File from SQL Server, Read its content, and load it in RichTextBox (Related comp

OBJECTIVE: I would like to read a text file from SQL Server 2000, read the text file content, and load its conntents in a RichTextBox

THINGS I'VE DONE AND HAVE WORKING:
1) I've successfully load a text file (ex: textFile.txt) in sql server database table column (with datatype Image)

2) I've also able to load the file using a Handler as below:

using System;
using System.Web;
using System.Data.SqlClient;

public class HandlerImage : IHttpHandler {

string connectionString;
public void ProcessRequest (HttpContext context)
{
connectionString = System.Configuration.ConfigurationManager.ConnectionStrings
["NWS_ScheduleSQL2000"].ConnectionString;
int ImageID = Convert.ToInt32(context.Request.QueryString["id"]);
SqlConnection myConnection = new SqlConnection(connectionString);

string Command = "SELECT [Image], Image_Type FROM Images WHERE Image_Id=@.Image_Id";
SqlCommand cmd = new SqlCommand(Command, myConnection);
cmd.Parameters.Add("@.Image_Id", System.Data.SqlDbType.Int).Value = ImageID;

SqlDataReader dr;

myConnection.Open();
cmd.Prepare();
dr = cmd.ExecuteReader();
if (dr.Read())
{ //WRITE IMAGE TO THE BROWSER
context.Response.ContentType = dr["Image_Type"].ToString();
context.Response.BinaryWrite((byte[])dr["Image"]);
}
myConnection.Close();
}

public bool IsReusable {
get {
return false;
}
}

}'>'>

<ahref='<%# "HandlerDocument.ashx?id=" + Eval("Doc_ID") %>'>

File

</a>
- Click on this link, I'll be able to download or view the file

WHAT I WANT TO DO, BUT HAVE PROBLEM:
- I would like to be able to read CONTENT of this file and load it in a string as below

StreamReader SR = new StreamReader()
SR = File.Open("File.txt");
String contentText = SR.Readline();
txtBox.text = contentText;

BUT THIS ONLY WORK FOR files in the server.
I would like to be able to read FILE CONTENTS from SQL Server.

PLEASE HELP. I really appreciate it.

I've figured it out, but it takes too long for my browser to load, and end up with string that include many squares like "Submitted 22155 1966 Servers".

Below is my code that goes with what is above.

Stream theFile =newMemoryStream((byte[])dr["Doc"]);

StreamReader SR =newStreamReader(theFile);

String contentText = SR.ReadToEnd();

If anybody can tell me why it's so slower to load the content of the text file on browser compare to uploading it to the database, and a way to speed it up

I'll really appreciate it.

Thanks,

No comments:

Post a Comment