I'm making a program with c# and sql server and I have a problem , I hope if anyone help me .
I will but the database on pc and the program will be installed in other PCs , and app pcs' program connected to that database.
the program saving documents (word -excel) as binary ,using this code:
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
private void button1_Click(object sender, EventArgs e)
{
string dt = dateTimePicker1.Value.ToShortDateString();
byte[] red = ReadFile(textBox3.Text);
con.Open();
string qry = "insert into documents ([Account no],Name,[Phone number],Date,[Document name],Document,Type) values(#accon,#name,#phone,#date,#docname,#doc,#type)";
//Initialize SqlCommand object for insert.
SqlCommand SqlCom = new SqlCommand(qry, con);
//We are passing Original Image Path and Image byte data as sql parameters.
SqlCom.Parameters.Add(new SqlParameter("#accon", textBox1.Text));
SqlCom.Parameters.Add(new SqlParameter("#name", textBox2.Text));
SqlCom.Parameters.Add(new SqlParameter("#phone", textBox3.Text));
SqlCom.Parameters.Add(new SqlParameter("#date", dt));
SqlCom.Parameters.Add(new SqlParameter("#docname", textBox1.Text));
SqlCom.Parameters.Add(new SqlParameter("#doc", (object)red));
SqlCom.Parameters.Add(new SqlParameter("#type", (object)textBox2.Text));
SqlCom.ExecuteNonQuery();
con.Close();
MessageBox.Show("done");
}
the problem : that I don't know how to retrieve saved documents in database and open it with Microsoft word or Microsoft Excel according to their types.
I want to select specific document form database and open it
Thanks in advance
String connStr = "connection string";
// add here extension that depends on your file type
string fileName = Path.GetTempFileName() + ".doc";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
// you have to distinguish here which document, I assume that there is an `id` column
cmd.CommandText = "select document from documents where id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
int size = 1024 * 1024;
byte[] buffer = new byte[size];
int readBytes = 0;
int index = 0;
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
while ((readBytes = (int)dr.GetBytes(0, index, buffer, 0, size)) > 0)
{
fs.Write(buffer, 0, readBytes);
index += readBytes;
}
}
}
}
}
}
// open your file, the proper application will be executed because of proper file extension
Process prc = new Process();
prc.StartInfo.FileName = fileName;
prc.Start();
After you have retrieved your document from the database (or any type of storage you care to use on the server) you should save the document in the windows temporary folder (Path.GetSpecialFolder) and use the Word Interop library to start word (or excel using its own interop library) with the document you just saved.
var temporayFileName = Path.GetRandomFileName();
var temporaryFileStream = File.Open(temporaryFileName, FileMode.Create);
var memoryStream = documentRepository.Get(...);
memoryStream.CopyTo(temporaryFileStream);
// Word App
dynamic wordApp = new Application { Visible = true };
var doc = wordApp.Documents.Add(TemplateName);
templatedDocument.Activate();
(See this document for more information about starting and manipulating word:
http://msdn.microsoft.com/en-us/magazine/ff714583.aspx)
.
The crux is Response.ContentType:
Response.ContentType = "application/vnd.xls"; // for excel
Response.ContentType = "application/ms-word"; // for word
Response.ContentType = "image/jpg";//for jpg images
It is advised to store content type also in database so that your code will be generic and can display/store any type of file
System.Data.SqlClient.SqlDataReader rdr = null;
System.Data.SqlClient.SqlConnection conn = null;
System.Data.SqlClient.SqlCommand selcmd = null;
try
{
conn = new System.Data.SqlClient.SqlConnection(
System.Configuration.ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString);
selcmd = new System.Data.SqlClient.SqlCommand(
"select pic1 from msg where msgid=" + Request.QueryString["imgid"],
conn);
conn.Open();
rdr = selcmd.ExecuteReader();
while (rdr.Read())
{
Response.ContentType = "image/jpg";
Response.BinaryWrite((byte[])rdr["pic1"]);
}
if (rdr != null)
rdr.Close();
}
finally
{
if (conn != null)
conn.Close();
}
Related
I am inserting docx file into an SQL table like ,
DECLARE #file AS VARBINARY(MAX)
SELECT #file = CAST(bulkcolumn AS VARBINARY(MAX))
FROM OPENROWSET(
BULK
'D:\abc.docx',
SINGLE_BLOB ) AS x
INSERT INTO ItemData(Id,fileData)
SELECT NEWID(),#file
Now file inserted into table properly.
Read File
For reading file, I am using bellow code :
"ItemNumber" is used for identity.
Everything is working fine.
But I have to show that file to the Document Viewer in WPF.
string cmdString = "Select fileData.PathName() As Path from ItemData where ItemNumber = '" + itemNumber + "' ";
SqlCommand cmd = new SqlCommand(cmdString, conn);
Object pathObj = cmd.ExecuteScalar();
if (DBNull.Value != pathObj)
filePath = (string)pathObj;
else
{
throw new System.Exception("fileData.PathName() failed to read the path name for the Chart column.");
}
this.wbControl.Navigate(filePath);
SqlTransaction transaction = conn.BeginTransaction("mainTranaction");
cmd.Transaction = transaction;
cmd.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
Object obj = cmd.ExecuteScalar();
byte[] txContext = (byte[])obj;
SqlFileStream sqlFileStream = new SqlFileStream(filePath, txContext, FileAccess.ReadWrite);
//byte[] buffer2 = new byte[(int)sqlFileStream.Length];
byte[] buffer = new byte[512];
int numBytes = 0;
string someData = "EKG data.";
Encoding unicode = Encoding.GetEncoding(0);
sqlFileStream.Write(unicode.GetBytes(someData.ToCharArray()), 0, someData.Length);
sqlFileStream.Seek(0L, SeekOrigin.Begin);
numBytes = sqlFileStream.Read(buffer, 0, buffer.Length);
string readData = unicode.GetString(buffer);
if (numBytes != 0)
Console.WriteLine(readData);
//Because reading and writing are finished, FILESTREAM
//must be closed. This closes the c# FileStream class,
//but does not necessarily close the the underlying
//FILESTREAM handle.
sqlFileStream.Close();
//The final step is to commit or roll back the read and write
//operations that were performed on the FILESTREAM BLOB.
cmd.Transaction.Commit();
How to I display SqlFileStream to Document Viewer in WPF?
I am storing docx file in database.
Here i Saved .Doc files in Database and i used varbinary(MAX) Datatype. Now I want to bind the varbinary(MAX) field to Richtext box, Here i am used bellow code to Read binary format data to string type.
string Query = "Select Name, ContentType, DocFileText from <TableNAme> where Id=5";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
SqlDataReader sqlRead = cmd.ExecuteReader();
while (sqlRead.Read())
{
byte[] fileData = ((byte[])sqlRead["DocFileText"]);
Richtextbox1.Text = Encoding.ASCII.GetString(fileData);
}
but the data should be in unreadable format like :
PK!0?(r?[Content_Types].xml ?(??T?n?0?W??D?V??????[??0??z??l?I?Q?B? \"%?????????l ?w%?=???^i7+???%?g&??0?A?6?l4??L60#????S ????X??&??V$z?3??3 ??????%p)O5?????5}?:?`?e????V?DFK??)_:?K%?)?l??\?!??U?'?v?7?&j?X??*,??+W^.,???????W????k??D?????X?????>??N!??FZ??&0m??ly??)?q?9??d}???#??????????R??/??s???*&:t??g?????????8Y?O?[??&V0}?X????????>?#??;?F?io.????PK!???N_rels/.rels ?(????JA???a?}7? "???H?w"????w?????? ?P?^????O?????;?<?aY????`G?kxm??PY?[??g G??ino?/"f3??\???T??I S??????????W????Y ig?#??X6_?]7~ f?????ao?.b*lI?r?j)?,l0?%??b? 6?i???D?_???, ? ???|u?Z^t??y??;!Y,}{?C??/h>??PK!??? ?word/_rels/document.xml.rels ?(????J?0?????n????l?????v???$?j?????..??K`?????0??L'????YI?#[????????? D mK?9? ?Ooovo?i?G?i? ?? Q?,e(4:D?G?7??F????.>u?r?[???^x?C???{??s??????_\q4h?J?H?????FRpR"?ya?* ?p???d?x{49z??Dp?? ?kB?Nc)?3Ybx\??r?2?w3?????&?7??Vr&?#??oK??PK!??????2word/document.xml?Y[O?0~????r????BiCH????.???????_?s?84?-a-#??;>??|>N..??P?S.?u???5{l??}???{??5!I??#???Z#sl?}?????M??iuK??B?? ???]????=???O?F??o????ba?)??Nw8,Ht'pn6??P7??p)N?*97?tl???#'L???????se~??;?Y??;???}?K?????v???M??????K???j?>U????+g?^U|?????C N???M?~%????a???????H??m?/?&?M_?i=??????VQN?0?J?#??l??J?|!U??4[]S%??7?$?i7:?bB???Nl??{uH5""3%hA?:?g?????n???:????#??xi%?z_vZ?*U?m??u??2?Jq??'?3?h???1Q?, ??????'??;??g?? ?Ev?????0$??`XmtGr??!?e_?}v??#??????????dT?h+?j-,A?%#???6? ??w?????|UOQ4????E?ga?V???#?????w2?|????????~????WH??X????t?^^???O????????lK?=?K????? ?93?.????????????ev?j??????|?4?y0??e?????=FV ??^?r?Zh9#??_vvsN3?r????????\m?]??1Y n4?X/2?.??`?%O?a????A??l??????N?d???????PK!?????Pword/theme/theme1.xml?YOo?6??w toc'vu????-M?n?i???P?#?I}?????a??m?a[????4?:l???GR??X^?6???>$?????????!)O?^?r?C$?y#?????/?yH*??????)?????????UDb?`}"?q???J?????X^?)I`n?E???p)???li?V[]?1M???G?M?Ge???D?????3Vq%'#q??????$?8??K?????)f?w9:????? x}r?x????w???r?:\TZaG?*?y8I?j?bR??c|X??????I u3KG?nD1?NIB?s??? ??R??u???K>V?.EL+M2?#'?f??i~?V??vl?{u8??z??H? ?*????:?(W???? ~??J??T?e\O*?tHG??HY???}KN??P?*???????T???9/#??A7?qZ??$*c????qU??n??w?N??%??O??i??4=3??P?? ????1?P?m\\9?????????M???2a?D?]?;Yt?\????[x??????]?}Wr??|?]??g-??? eW? ?)6-r??CS?j?? i?d ?D??A???IqbJ#x????6k???#??A?Sh???&??t(Q?%??p%m??&]?caSl=?X???????\P?1?Mh?9?M???V?dDA??aV?B??[??fJ???P|8???A?V^???f ?H??n???-??"??d>?z???n????? ?????>??b???&?????2??v????Ky?????D:????,AGm??\nz??i?????.u??YC?6?OMf??3o?r??$??5?????NH?T[XF64?T,?????M0?E)`#?5?XY?`???;??%?1?U???m;???R>QD????D?cp?U?'??&LE?/p???m????%]?????8fi??r?S4?d7y\?`?J??n??????I?R???3U?~7+?????#??m?q?BiD??????????i*?L6?9??m?Y&?????i???HE??=(K&?N!V??.K?e?LD????{D ????vE???de??N????e?(?MN9??R??6????&3(??a????/D??U?z???)???D????_??k??wXXub?????(?9??8?????????????<4??u?>?p?? ???F????
Here i used
Encoding.UTF8.GetString(fileData);
Encoding.Unicode.GetString(fileData);
but these are also not working.
How can i read Doc file from database to richtextbox ?
And My Uploaded Code is:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
Stream str = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(str);
Byte[] size = br.ReadBytes((int) str.Length);
using (SqlConnection con = new SqlConnection(Connstring))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into Gtrans(Name, ContentType, DocFileText) values(#Name, #ContentType, #DocFileText)";
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/word");
cmd.Parameters.AddWithValue("#DocFileText", size);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Okay there are two problems with your approach.
Point 1 (If you are using winforms):
If you like to load rtf text into a RichTextBox then you have to use the Rtf property of the RichTextBox. Not the Text property. See this for more information.
Point 2:
You can't open .doc in rtf just by passing the .doc string to rtf. .doc is something other that rtf.
The good news: it is possible, the bad: you need MS Word.
Add reference to "Microsoft Word 15.0 Object Library" is under the 'Com' section of the references window
Use this code to convert the doc file to rtf file
.
byte[] yourDocData = null; // in your case (byte[])sqlRead["DocFileText"]
// Save your data as file so word can read it
var tmpFile = Path.GetTempFileName();
using (var fileStream = new FileStream(tmpFile, FileMode.Append, FileAccess.Write))
using (var writer = new BinaryWriter(fileStream)) {
writer.Write(yourDocData);
}
// Convert .doc to .rtf
var newWordFile = (object) tmpFile;
var newRtfFile = (object) Path.GetTempFileName();
var wordObject = new Microsoft.Office.Interop.Word.Application();
var docs = wordObject.Documents.Open(ref newWordFile);
docs.SaveAs(ref newRtfFile, WdSaveFormat.wdFormatRTF);
// This is your rtf code
var yourRtfCode = File.ReadAllText(newRtfFile.ToString());
// Dispose
docs.Close();
wordObject.Quit();
source
Important
Use the same Encoding for saving / loading your .doc from the database!
Set the yourRtfCode not to the text-property of your control but to the property accepting rtf-text
protected void btnDownload_Click(object sender, EventArgs e)
{
SqlCommand Command = connection.CreateCommand();
SqlDataReader SQLRD;
Command.CommandText = "Select *from Attendance";
connection.Open();
SQLRD = Command.ExecuteReader();
string data = "";
while (SQLRD.Read())
{
data += SQLRD[0].ToString();
data += SQLRD[1].ToString();
}
SQLRD.Close();
connection.Close();
string filename = #"C:\download.csv";
FileStream fs = new FileStream(filename,FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(data);
sw.Flush();
sw.Close();
fs.Close(); }
This is what I have so far. I want to store all the data from the above query in a file. This file will be downloaded.
protected void btnDownload_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
MySqlCommand myCommand = myConn.CreateCommand();
MySqlDataReader SQLRD;
myCommand.CommandText = "SELECT * FROM Attendance";
connection.Open();
SQLRD = myCommand.ExecuteReader();
string data="";
while (SQLRD.Read())
{
data += "Row data, arrange how you want";//SQLRD[0].Tostring();-->first coloum
}
SQLRD.Close();
connection.Close();
string filename = "F:\file1.txt"; //with path
FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(data);
sw.Flush();
sw.Close();
fs.Close();
}
EDITED CODE: just copy paste in your code and change filename path
MySqlCommand Command = connection.CreateCommand();
connection.Open();
//SqlCommand Command = new SqlCommand();
MySqlDataReader SQLRD;
Command.CommandText = "Select * from Attendance";
//connection.Open();
SQLRD = Command.ExecuteReader();
string data = "";
while (SQLRD.Read())
{
data += SQLRD[0].ToString()+"\n";
data += SQLRD[1].ToString()+"\n";
}
SQLRD.Close();
connection.Close();
string filename = #"F:\download.csv";
FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(data);
sw.Flush();
sw.Close();
fs.Close();
}
Your code to save the data to file will change based on the file format that you want. Once you save the file, use HttpResponse.TransmitFile to push the file to browser. For example, the template code would be
protected void btnDownload_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
string query = "SELECT * FROM Attendance";
// Fetch data using data reader or data adapter
...
// Save the data to file in required format
string filePath;
....
// Push the file from response
Response.ContentType = "text/csv"; // set as per file type e.g. text/plain, text/xml etc
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv"); // will prompt user for save file dialog, use inline instead of attachment to suppress the dialog
Response.TransmitFile(filePath);
}
See other answers for code for storing the file in some format such as xml/csv.
You would be best served by using serialization. I would create a structured object using the Active Record design pattern.
I would then output that object using XML Serialization to an XML object. I would then save that XML to the disk and deserialize it later and use it as if nothing happened.
See: How to serialize and object to XML in C# on MSDN.
The easiest way to write to file is using DataTable.WriteXml method which writes the entire data of data table to an XML file and this file later can be downloaded:
SqlDataAdapter sqlAdap = new SqlDataAdapter(query, connection);
DataTable dt = new DataTable();
sqlAdap.Fill(dt);
string filePath = Server.MapPath("~/filename.xml");
dt.WriteXml(filePath);
But if you want to write this data to some particular format, say csv, you have to loop through all the rows and using StreamWrite class you can write it to file. The code below is just to give you an idea, i haven't added any type checking or checks for null.
string filePath = Server.MapPath("~/somefile.csv");
System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath);
foreach (DataRow r in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(r[i].ToString());
sw.Write(",");
}
sw.WriteLine();
}
sw.Close();
You can export it as a DataSet to disk like this:
using (var conn = new SqlConnection(#"<your conn str>"))
{
var ds = new DataSet();
using (var invoiceCmd = conn.CreateCommand())
//One of these per table to export
using(var invoiceAdapter = new SqlDataAdapter(invoiceCmd))
{
invoiceCmd.CommandText = "SELECT * FROM Attendance";
invoiceAdapter.Fill(ds, "Attendance");
}
ds.WriteXml(#"C:\temp\foo.xml");
}
I have to persist a .csv in my database, but for a more testable application I prefer don't use procedures.
Basically I just generate a file and the next instruction is put this in database.
Someone have some clue about best way to do this in code?
Here is an example to insert blob data in oracle using c# and procedures (you said prefer that means you may).
using System;
using System.Data;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System.IO;
using System.Text;
//Step 1
// Connect to database
// Note: Modify User Id, Password, Data Source as per your database setup
string constr = "User Id=Scott;Password=tiger;Data Source=orcl9i";
OracleConnection con = new OracleConnection(constr);
con.Open();
Console.WriteLine("Connected to database!");
// Step 2
// Note: Modify the Source and Destination location
// of the image as per your machine settings
String SourceLoc = "D:/Images/photo.jpg";
String DestinationLoc = "D:/Images/TestImage.jpg";
// provide read access to the file
FileStream fs = new FileStream(SourceLoc, FileMode.Open,FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
// Step 3
// Create Anonymous PL/SQL block string
String block = " BEGIN " +
" INSERT INTO testblob (id, photo) VALUES (100, :1); " +
" SELECT photo into :2 from testblob WHERE id = 100; " +
" END; ";
// Set command to create Anonymous PL/SQL Block
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = con;
// Since executing an anonymous PL/SQL block, setting the command type
// as Text instead of StoredProcedure
cmd.CommandType = CommandType.Text;
// Step 4
// Setting Oracle parameters
// Bind the parameter as OracleDbType.Blob to command for inserting image
OracleParameter param = cmd.Parameters.Add("blobtodb", OracleDbType.Blob);
param.Direction = ParameterDirection.Input;
// Assign Byte Array to Oracle Parameter
param.Value = ImageData;
// Bind the parameter as OracleDbType.Blob to command for retrieving the image
OracleParameter param2 = cmd.Parameters.Add("blobfromdb", OracleDbType.Blob);
param2.Direction = ParameterDirection.Output;
// Step 5
// Execute the Anonymous PL/SQL Block
// The anonymous PL/SQL block inserts the image to the
// database and then retrieves the images as an output parameter
cmd.ExecuteNonQuery();
Console.WriteLine("Image file inserted to database from " + SourceLoc);
// Step 6
// Save the retrieved image to the DestinationLoc in the file system
// Create a byte array
byte[] byteData = new byte[0];
// fetch the value of Oracle parameter into the byte array
byteData = (byte[])((OracleBlob)(cmd.Parameters[1].Value)).Value;
// get the length of the byte array
int ArraySize = new int();
ArraySize = byteData.GetUpperBound(0);
// Write the Blob data fetched from database to the filesystem at the
// destination location
FileStream fs1 = new FileStream(#DestinationLoc,
FileMode.OpenOrCreate, FileAccess.Write);
fs1.Write(byteData, 0,ArraySize);
fs1.Close();
Console.WriteLine("Image saved to " + DestinationLoc + " successfully !");
Console.WriteLine("");
Console.WriteLine("***********************************************************");
Console.WriteLine("Before running this application again, execute 'Listing 1' ");
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Read Image Bytes into a byte array
byte[] blob = ReadFile(txtPath.Text);
//Initialize Oracle Server Connection
con = new OracleConnection(conString);
//Set insert query
string qry = "insert into Imgpn (imgpath,photo) values('" + txtPath.Text + "'," + " :BlobParameter )";
OracleParameter blobParameter = new OracleParameter();
blobParameter.OracleType = OracleType.Blob;
blobParameter.ParameterName = "BlobParameter";
blobParameter.Value = blob;
//Initialize OracleCommand object for insert.
cmd = new OracleCommand(qry, con);
//We are passing Name and Blob byte data as Oracle parameters.
cmd.Parameters.Add(blobParameter);
//Open connection and execute insert query.
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Image added to blob field");
GetImagesFromDatabase();
cmd.Dispose();
con.Close();
//this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}
void GetImagesFromDatabase()
{
try
{
//Initialize Oracle connection.
con = new OracleConnection(conString);
//MessageBox.Show("Connection Successfull");
//Initialize Oracle adapter.
OracleDataAdapter oda = new OracleDataAdapter("Select * from Imgpn", con);
//Initialize Dataset.
DataSet DS = new DataSet();
//Fill dataset with ImagesStore table.
oda.Fill(DS, "Imgpn");
//Fill Grid with dataset.
dataGridView1.DataSource = DS.Tables["Imgpn"];
//
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
here is the simple way to insert image into oracle database ane retrieve ane show in datagridview
I am developing a C# application that has an Access database. What I want to do is allow a user to select an image through an "openfiledialog." I then want to store the image in one of the table of the access database in a BLOB field. I have searched over the internet, but found nothing helpful. I hope you can help me.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// textBox1.Show(openFileDialog1.FileName.ToString());
// MessageBox.Show(openFileDialog1.FileName.ToString());
textBox1.Text = openFileDialog1.FileName.ToString();
String filename = openFileDialog1.FileName.ToString();
byte[] buffer = File.ReadAllBytes(filename);
using (var conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Policias.accdb"))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO DetallesMunicipio(imagen) VALUES (#imagen)";
cmd.Parameters.AddWithValue("#imagen", buffer);
conn.Open();
cmd.ExecuteNonQuery();
}
}
else
{
MessageBox.Show("Porfavor selecciona una imagen");
}
}
but now how can I be sure that is stored in the access database?
Example:
string filename = "foo.txt"; // TODO: fetch from file dialog
byte[] buffer = File.ReadAllBytes(filename);
using (var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=foo.mdb"))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO MyTable VALUES (#Name, #Data)";
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#Data", buffer);
cmd.ExecuteNonQuery();
}
What you will want to do is something similar to the following.
using (OpenFileDialog fileDialog = new OpenFileDialog){
if(fileDialog.ShowDialog == DialogResult.OK){
using (System.IO.FileInfo fileToSave = new System.IO.FileInfo(fileDialog.FilePath)){
MemoryStream ms = System.IO.FileStream(fileToSave.FullNae, IO.FileMode.Open);
//Here you can copy the ms over to a byte array to save into your blob in your database.
}
}
}
I would use File.ReeadAllBytes(file) and save the byte[] there in the DB.