How to retrieve any kind of files from sql database using C# - c#

I tried a code from the internet and it's working fine. It can upload any kind of file to a SQL database and can retrieve it from SQL database.
But my problem is how can i open any kind of file from SQL database without saving it in the computer.I want to open stored file without saving. like if it is a excel file i want to open it in excel. And then user can save it or not. thank you Here is my code..
private void button6_Click(object sender, EventArgs e)
{
SaveAttachment(sfdMain, gridViewMain);
FillDataGrid(gridViewMain, strQuery_AllAttachments); // refresh grid
}
private void SaveAttachment(SaveFileDialog objSfd, DataGridView objGrid)
{
string strId = objGrid.SelectedRows[0].Cells["ID"].Value.ToString();
if (!string.IsNullOrEmpty(strId))
{
SqlCommand sqlCmd = new SqlCommand(strQuery_GetAttachmentById, objConn);
sqlCmd.Parameters.AddWithValue("#attachId", strId);
SqlDataAdapter objAdapter = new SqlDataAdapter(sqlCmd);
DataTable objTable = new DataTable();
DataRow objRow;
objAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(objAdapter);
objAdapter.Fill(objTable);
objRow = objTable.Rows[0];
byte[] objData;
objData = (byte[])objRow["attachment"];
if (objSfd.ShowDialog() != DialogResult.Cancel)
{
string strFileToSave = objSfd.FileName;
FileStream objFileStream =
new FileStream(strFileToSave, FileMode.Create, FileAccess.Read);
objFileStream.Write(objData, 0, objData.Length);
objFileStream.Close();
}
}
}
private void button5_Click(object sender, EventArgs e)
{
if (ofdMain.ShowDialog() != DialogResult.Cancel)
{
CreateAttachment(ofdMain.FileName); //upload the attachment
}
FillDataGrid(gridViewMain, strQuery_AllAttachments); //refresh grid
}
private void CreateAttachment(string strFile)
{
SqlDataAdapter objAdapter =
new SqlDataAdapter(strQuery_AllAttachments_AllFields, objConn);
objAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
SqlCommandBuilder objCmdBuilder = new SqlCommandBuilder(objAdapter);
DataTable objTable = new DataTable();
FileStream objFileStream =
new FileStream(strFile, FileMode.Open, FileAccess.Read);
int intLength = Convert.ToInt32(objFileStream.Length);
byte[] objData;
objData = new byte[intLength];
DataRow objRow;
string[] strPath = strFile.Split(Convert.ToChar(#"\"));
objAdapter.Fill(objTable);
objFileStream.Read(objData, 0, intLength);
objFileStream.Close();
objRow = objTable.NewRow();
//clip the full path - we just want last part!
objRow["fileName"] = strPath[strPath.Length - 1];
objRow["fileSize"] = intLength / 1024; // KB instead of bytes
objRow["attachment"] = objData; //our file
objTable.Rows.Add(objRow); //add our new record
objAdapter.Update(objTable);
}

Just as a warning, you may be going down the wrong route. Putting files in your database is rarely the way to go. It can cause you problems, not just in size but speed and load on your database.
Instead, why don't you investigate one of the many options of cloud storage? Azure for example has private blob storage that you can use, and it is built for this purpose. It also has an emulator so you can test it locally.

Related

How to save 1 file PDF to SQL Server with WinForm

Code query database:
I can't save the PDF files to my database, I have a serious problem in the database storage area.
public void ADDWORK(String MAW, string NAMEW, string IDUSER, bool Image,string room, byte[] document,string content,bool donework)
{
String strSql = string.Format("INSERT INTO WORK(IDWORD,NAMEWORk,IDUSER,IMAGES,IDROOM,DOCUMENTS,CONTENT,DONEWORK)VALUES('{0}',N'{1}',N'{2}','{3}',N'{4}',N'{5}',N'{6}',N'{7}')"
, MAW, NAMEW, IDUSER, Image,room,document,content,donework);
db.ExecuteNonQuery(strSql);
}
Code call function:
byte[] pdf;
public void UploadFlie(string file)
{
FileStream fileStream = File.OpenRead(file);
byte[] contents = new byte[fileStream.Length];
fileStream.Read(contents, 0, (int)fileStream.Length);
fileStream.Close();
pdf = contents;
}
private void button1_Click(object sender, EventArgs e)
{
UploadFlie(filename);
dg.ADDWORK(idword, textBox1.Text,"1", false,"ROOM1", pdf, richTextBox1.Text, false);
MessageBox.Show("Done!");
}
here is my example how to get any file and save it on database.
I use two diffrent methods
Saving byte array.
Saving Stream
First you need to create column varbinary(MAX) in my case I called it - PdfFile
and PdfExtn column to save the type of the file As varchar(10) (You can use 4).
Saving byte array:
private void btnGetFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
string extn = new FileInfo(file).Extension;
try
{
byte[] fileBytes = File.ReadAllBytes(file);
string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (#Id,#FirstName,#LastName,#Email,#Password,#PdfFile,#FileExtn)";
List<SqlParameter> l = new List<SqlParameter>();
l.Add(new SqlParameter("#Id", "101"));
l.Add(new SqlParameter("#FirstName", "Aviv"));
l.Add(new SqlParameter("#LastName", "Halevy"));
l.Add(new SqlParameter("#Email", "Assadsa#gmail.com"));
l.Add(new SqlParameter("#Password", "123456"));
SqlParameter sp = new SqlParameter("#PdfFile", SqlDbType.VarBinary, -1);
sp.Value = fileBytes;
l.Add(sp);
l.Add(new SqlParameter("#FileExtn", extn));
if (DAL.Database.ParametersCommand(cmd, l) > 0)
textBox1.Text = "SUCCESS! Save with byte array";
}
catch (IOException ex)
{
}
}
}
Write the file from bytes:
private void btnReadFromDb_Click(object sender, EventArgs e)
{
string cmd = "SELECT * FROM Employee WHERE Id = '101'";
string path = "YOUR_PATH\\Test";
DataTable dt = DAL.Database.GetDataTable(cmd);
if (dt != null && dt.Rows.Count > 0)
{
Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
string extn = dt.Rows[0]["FileExtn"].ToString();
path = Path.Combine(path, "Test321"+extn);
File.WriteAllBytes(path, file);
Process.Start(path);
}
}
And the result:
Using Stream
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
using (Stream stream = File.OpenRead(file))
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
string extn = new FileInfo(file).Extension;
string cmd = "INSERT INTO Employee(Id,FirstName,LastName,Email,Password,PdfFile,FileExtn) VALUES (#Id,#FirstName,#LastName,#Email,#Password,#PdfFile,#FileExtn)";
List<SqlParameter> l = new List<SqlParameter>();
l.Add(new SqlParameter("#Id", "102"));
l.Add(new SqlParameter("#FirstName", "Aviv"));
l.Add(new SqlParameter("#LastName", "Halevy"));
l.Add(new SqlParameter("#Email", "Assadsa#gmail.com"));
l.Add(new SqlParameter("#Password", "123456"));
l.Add(new SqlParameter("#PdfFile", buffer));
l.Add(new SqlParameter("#FileExtn", extn));
if (DAL.Database.ParametersCommand(cmd, l) > 0)
textBox1.Text = "SUCCESS! Save with Stream";
}
}
}
Write the file from stream:
private void button2_Click(object sender, EventArgs e)
{
string cmd = "SELECT * FROM Employee WHERE ID = '102'";
string path = "YOUR_PATH\\Test";
DataTable dt = DAL.Database.GetDataTable(cmd);
if (dt != null && dt.Rows.Count > 0)
{
Byte[] file = (Byte[])dt.Rows[0]["PdfFile"];
string extn = dt.Rows[0]["FileExtn"].ToString();
path = Path.Combine(path, "Test123"+extn);
File.WriteAllBytes(path, file);
Process.Start(path);
}
}
And the result:
Note:
In my examples the DAL project has a static methods that runs my sql commands.

Import multiple excel sheet into gridview using exceldatareader

currently I able to import an excel file into gridview by using exceldatareader library. Now, I want to further improve to import multiple excel sheet into gridview. This is the output I wish to do. ImageOutput
I able to get the excel sheet name into the dropdownlist but I have no idea how to get the data from the second sheet. I tried google but still cant found any answer yet.
So now my problem how can I select the sheet name from the dropdownlist and show that sheet data in the gridview.
Below is my code:
public partial class ReadExcel : System.Web.UI.Page
{
DataSet result;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLoad_Click(object sender, EventArgs e)
{
dataUpload();
}
protected void dataUpload()
{
if (FileUpload1.HasFile)
{
string path = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string filepath = Server.MapPath("~/" + path);
FileUpload1.SaveAs(filepath);
FileStream stream = File.Open(filepath, FileMode.Open, FileAccess.Read);
//for excel 2003
// IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
// for Excel 2007
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
result = excelReader.AsDataSet();
ddlSheet.Items.Clear();
foreach(DataTable dt in result.Tables)
{
ddlSheet.Items.Add(dt.TableName);
}
//excelReader.IsFirstRowAsColumnNames = true;
while (excelReader.Read())
{
// int i = excelReader.GetInt32(0);
GridView1.DataSource = result;
GridView1.DataBind();
}
}
else
{
lblError.Text = "Unable to upload the selected file. Please check the selected file path or confirm that the file is not blank!";
}
}
protected void ddlSheet_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.DataSource = result;
GridView1.DataBind();
}
}
Hummm, interesting. I've never tried what you described here, but I think the link below will help you get started.
https://msdn.microsoft.com/en-us/library/aa480727.aspx?f=255&MSPPError=-2147217396
Also, below is a small sample of code to get things going.
You can use the excel library from this link http://code.google.com/p/excellibrary/. There is actually an example code provided on this page, it demonstrates how to read from an excel file.
using ExcelLibrary.SpreadSheet;
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];
// iterate with a proper condition, at the moment it will iterate with a given length!
for (int i = 0; i < length; i++)
{
comboBox.Items.Add(sheet.Cells[i,column_index].Value);
}
Your result is a DataSet object that has Tables[] property and ExcelDataReader stores each sheet as a table.
So, I think you should change
GridView1.DataSource = result;
to
GridView1.DataSource = result.Tables[ddlSheet.SelectedText];

How to save images in sql server using winform?

i am trying to save images like bmp,jpg,gif & png into sql server database. but not able to save all the formats into database. Only png image is getting saved into database. if trying to save jpeg, .bmp & .gif images, it's showing error "A generic error occured in GDI+". What is the problem?
private void InitializeOpenFileDialog()
{
try
{
this.openFileDialog1 = new OpenFileDialog();
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|" + "All files (*.*)|*.*";
//"image files|*.jpg;*.png;*.gif;*.bmp;.*;";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
}
catch(Exception es){
MessageBox.Show(es.Message);
}
}
//load picture
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
MemoryStream ms1 = new MemoryStream();
pictureBox2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
// byte[] img_arr1 = ms1.ToArray();
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
SqlConnection con = new SqlConnection(#"data source=xdfgh\ALEXDAVE;database=x1234;UID=sa;password=x67890");
con.Open();
SqlCommand cmd = new SqlCommand("insert into myTable(enrolmentno,aadhaarno,name,fname,address,dob,gender,picimage)values(#a,#b,#c,#d,#e,#f,#g,#h)", con);
cmd.Parameters.AddWithValue("#a", enrolmentno_txt.Text);
cmd.Parameters.AddWithValue("#b", aadhaarno_txt.Text);
cmd.Parameters.AddWithValue("#c", name_txt.Text);
cmd.Parameters.AddWithValue("#d", fname_txt.Text);
cmd.Parameters.AddWithValue("#e", address_txt.Text);
cmd.Parameters.AddWithValue("#f", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#g", gender);
cmd.Parameters.AddWithValue("#h", img_arr1);
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Data inserted successfully");
else
MessageBox.Show("Data is not inserted in database");
con.Close();
}
catch(Exception es){
MessageBox.Show(es.Message);
}
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
this.Activate();
string[] files = openFileDialog1.FileNames;
try
{
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
FileStream fileStream = fileInfo.OpenRead();
pictureBox2.Image = Image.FromStream(fileStream);
Application.DoEvents();
fileStream.Close();
}
}
//es
catch (Exception)
{
MessageBox.Show("please select only image files.");
}
}
Are you sure the the image is valid?
What line are you getting the error on?
Like the error indicates, it's a GDI error, and not a SQL Error.
You can remove the need for GDI by replacing the following lines of code
MemoryStream ms1 = new MemoryStream();
pictureBox2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
with this
byte[] img_arr1 = System.IO.File.ReadAllBytes(fileName);
where fileName is the file that was selected

Visual C# Express. Data can be save but until I close Visual C#

This Is the code for Adding the new Item...
private KrystalCafeDatabaseEntities kce = new KrystalCafeDatabaseEntities();
private Byte[] byteBLOBData;
public AddItem()
{
InitializeComponent();
cmbCategory.DataSource = kce.tblItemTypes;
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "ItemType";
}
private void btnUpload_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
fsBLOBFile.Close();
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pbImage.Image = Image.FromStream(stmBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
tblItem Item = new tblItem();
Item.Name = txtName.Text;
Item.Price = decimal.Parse(txtPrice.Text);
Item.Image = byteBLOBData;
Item.ItemType = (int)cmbCategory.SelectedValue;
kce.AddTotblItems(Item);
kce.SaveChanges();
MessageBox.Show("Record Saved! :D");
}
}
}
The program runs normally but the data will only be stored for awhile, then If i either closed my program or edit my code the data I just added will be lost.
One likely error is that KrystalCafeDatabaseEntities opens a transaction and you need to commit that transaction after calling SaveChanges.

Convert DataTable to XML file and viceversa

I am having a problem with reading an XML file onto a DataTable. Initially, I am writing a Datatable to an XML file and saving it. Now, when I want to read the XML file back to the DataTable, it's not happening.
The following code is for writing the file:
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (myDT_For_DGV.Rows.Count != 0)
{
saveFileDialog1.ShowDialog();
saveFileDialog1.FileName = "checkOutFile.xml";
myDT_For_DGV.TableName = "CheckOutsAndIns";
myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
}
else
{
MessageBox.Show("Please add licences to DataGridView, you havent added any licences as of now", "Alert");
}
}
And for reading the file:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//write code to open file
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//myFile = openFileDialog1.FileName;
System.IO.MemoryStream xmlStream = new System.IO.MemoryStream();
xmlStream.Position = 0;
myDT_For_DGV.ReadXml(openFileDialog1.FileName);
//MessageBox.Show(openFileDialog1.FileName);
}
}
It might be easier to just work with the higher-level DataSet, like this:
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();
dataSet.Tables.Add(dataTable);
// Save to disk
dataSet.WriteXml(#"C:\MyDataset.xml");
// Read from disk
dataSet.ReadXml(#"C:\MyDataset.xml");
I fixed it, The Problem is, the tablename was assigned while saving but not while reading. So assign the table name globally, which will let it read and write without any problem.
so the code will be,
myDT_For_DGV.TableName = "CheckOutsAndIns";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
myDT_For_DGV.ReadXml(#openFileDialog1.FileName);
//MessageBox.Show(openFileDialog1.FileName);
}
//TO WRITE TO XML
if (myDT_For_DGV.Rows.Count != 0)
{
saveFileDialog1.ShowDialog();
saveFileDialog1.FileName = "checkOutFile.xml";
myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
}

Categories