C# SQL Server CE binary data recovery - c#

I am trying to save and read back pdf files in a SQL Server CE local database. I was able to save them as binary data in an Image column, but I don't know how to read them back and open the pdf file (original format).
Table Schema
Here is how I stored the PDF files:
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string filePath = textBox1.Text.ToString();
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
cmd.Parameters.AddWithValue("#Data",bytes);
cmd.ExecuteNonQuery();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
con.Dispose();
}

Try this
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string strQuery = "select Data where Name = #Name and ContentType = #ContentType";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
SqlCeDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.Read())
{
byte[] pdf = (byte[])reader["Data"];
File.WriteAllBytes(filename, pdf);
}
}
}
​

Related

Store a File Size in a database table using file upload controle

I need to save a file size in database table while uploading a file in using upload control.
i am simple pitching my upload control code here.
Please take a look.
protected void UploadFileControl(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);
using (SqlConnection con = new SqlConnection(con))
{
string str = "INSERT INTO XYZ VALUES (#FileName, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(str))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#FileName", fileName);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
This is simple upload control code.

lable don't show the message

i have problem with the lable when i upload file into database it not show any message
c#
protected void btnUpload_Click(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["homeworkConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles (FileName,ContentType,Number,Date,Data) values (#Name, #ContentType,#number,getDate(), #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#number", Session["id"].ToString());
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
fname.Visible = true;
fname.Text = "file Has been uploaded";
}
}
}
asp.net code
<asp:Label ID="fname" runat="server" Text="Label" Visible="False"></asp:Label>
the lable work with insert value but not work with the uploading file
protected void btnUpload_Click(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["homeworkConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles (FileName,ContentType,Number,Date,Data) values (#Name, #ContentType,#number,getDate(), #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#number", Session["id"].ToString());
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
fname.Visible = true;
fname.Text = "file Has been uploaded";
}
Try Like this...

Insert and read blob "pdf files" in oracle database with C#

I want to insert and read pdf blop to oracle with c#.I tried to do something below.I need insert oracle blop pdf file with C#.I am using this code
var fs = new FileStream(txtFileName.Text, FileMode.Open, FileAccess.Read);
var blobByte = new byte[fs.Length];
fs.Read(blobByte, 0, Convert.ToInt32(fs.Length));
fs.Close();
id=nextİd("tablename")//take ID_SEQ.NEXTVAL
var con = new racleConnection(System.Configuration.ConfigurationSettings.AppSettings["Orclsys"]);
var cmd = new OracleCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO tablename values(:id,:blopfile )";
OracleTransaction sqlTrans = con.BeginTransaction();
cmd.Transaction = sqlTrans;
try
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue(":id", Id);
var blobParameter = new OracleParameter();
blobParameter.OracleType = OracleType.Blob;
blobParameter.ParameterName = ":blopfile ";
blobParameter.Value = blobByte;
cmd.Parameters.Add(blobParameter);
cmd.ExecuteNonQuery();
Result = true;
sqlTrans.Commit();
}
catch(Exception ex)
{
}
finally
{
con.Close();
con.Dispose();
sqlTrans.Dispose();
cmd.Dispose();
}
so I want read this file from db and i am starting code but I can not continue.
How can I continue after.could you help me.!!
try
{
orcl.Connect(DbUser.System);
orcl.CommandText = "SELECT blopfile FROM tablename WHERE id= :id";
orcl.ClearParameters();
orcl.AddParameter(":id", id);
orcl.ExecuteDataReader();
var lob = orcl.DataReader.GetOracleLob(0);
var pdffile= new Bitmap(lob);
//
//how can I continue code here....
//
}
catch(Exception ex)
{
}

How to add an image into SQL Server database and retrieve it as in Gridview in ASP.net, C#

I'm developing an admin panel and a web service but how to add an image data into SQL Server database and retrieve it in admin panel in GridView? Everything adds fine, shows fine except the images. I'm using HTML Input (file) control. No errors just image is not displaying but lblTest shows accordingly.
And how to make my Button can ADD and Refresh so user can see the new data instantly.
Thank you!
Here is my C# code:
protected void Page_Load(object sender, EventArgs e)
{
showSplash();
}
string connStr = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
Int32 fileLength = 0;
protected void ButtonTest_Click(object sender, EventArgs e)
{
HttpPostedFile uploadFile = FileLogo.PostedFile;
fileLength = uploadFile.ContentLength;
if (fileLength == 0)
{
string filePath = Server.MapPath(#"\icon\no-photo-icon.jpg");
string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileLength = (Int32)fs.Length;
Byte[] fileByteArr = new Byte[fileLength];
fs.Read(fileByteArr, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArr);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine with no file";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
else
{
Byte[] fileByteArray = new Byte[fileLength];
Stream streamObject = uploadFile.InputStream;
streamObject.Read(fileByteArray, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArray);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
private void showSplash()
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select * from SPLASH", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(rdr);
GridViewAddSplash.DataSource = dt;
GridViewAddSplash.DataBind();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
My other related question links:
Ajax tabContainer:

Image Save and Retrieve in SQL Server in asp.net using c#

I am trying to save images in a SQL Server database.
I convert the image to bytes and store in SQL Server, but now I want to convert the saved bytes to an image and show it on a label in asp.net using c#.
I tried a lot but didn't find a solution.
Here is the code (convert bytes to Image)
if (fImage.HasFile)
{
if (fImage.PostedFile.ContentType == "image/jpg" || fImage.PostedFile.ContentType == "image/jpeg" || fImage.PostedFile.ContentType == "image/png")
{
int filelenght = fImage.PostedFile.ContentLength;
byte[] imagebytes = new byte[filelenght];
fImage.PostedFile.InputStream.Read(imagebytes, 0, filelenght);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into tbImage(Img) values(#img)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#img", imagebytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Image saved to database");
}
}
Something like this will convert Byte[] to Image:
MemoryStream ms = new MemoryStream(byte);
Image i = Image.FromStream(ms);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
byte[] img = (byte[])reader["img"];
MemoryStream ms = new MemoryStream(img);
PictureBox1.Image = Image.FromStream(ms);
}
}
con.Close();
All you need to do is to store the byte content in a variable and then write it to the File system:
var imgBlob = ... // Load the image binary array from the database
File.WriteAllBytes("path/to/file.jpg", imgBlob);
you can create a controller action to handle retrieving the image
public FileResult DownloadImage(int Photo_Id)
{
byte[] fileBytes = "get bytes from db here";
string fileName = "file name here"
return File(fileBytes, "contentType of the image" , fileName);
}
Thanks for your valuable reply.
i solve this problem with this one.
give a look.
int id = Convert.ToInt32(drpImage.SelectedValue);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id+"", con);
con.Open();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
byte[] img = (byte[])dr["img"];
string base64string = Convert.ToBase64String(img, 0, img.Length);
lblImage.Text += "<img src='data:image/png;base64," + base64string + "' alt='No Image' width='200px' vspace='5px' hspace='5px' />";
}
}
con.Close();

Categories