I have a C# application that reads images form a MS-access database and write the binary data from ole object and write it to the same image extension of the saved image but the problem is that the file is written in wrong format . here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection Dbconnection = new OleDbConnection();
OleDbDataAdapter Dataadapter;
DataTable localDataTable = new DataTable();
int rowposition = 0;
int rownumber = 0;
public Form1()
{
InitializeComponent();
}
private void ConnectToDatabase()
{
Dbconnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database.mdb";
Dbconnection.Open();
Dataadapter = new OleDbDataAdapter("SELECT * FROM `mody`", Dbconnection);
Dataadapter.Fill(localDataTable);
MessageBox.Show(localDataTable.Rows.Count.ToString());
if (localDataTable.Rows.Count != 0)
{
rowposition = localDataTable.Rows.Count;
}
}
private void Form1_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
private void btnToPB_Click(object sender, EventArgs e)
{
rownumber = 0;
pictureBox1.Image = ReadImageFromDB();
btnNext.Enabled = true;
btnPrev.Enabled = true;
}
private Image ReadImageFromDB()
{
Image fetchedImg=null;
if (rownumber >= 0)
{
byte[] fetchedimgbytes = (byte[])localDataTable.Rows[rownumber]["Img"];
string path = @"myimage.bmp";
using (MemoryStream inputStream = new MemoryStream(fetchedimgbytes))
{
using (Stream file = File.Create(path))
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
file.Write(buffer, 0, len);
}
}
}
return fetchedImg;
}
else
{
MessageBox.Show("no image");
return null;
}
}
}
}