I have created a method to read from my database, the database has a blob field that stores images. This method is used to read the Image as well as every other field. When i run my Application it works and the form displays all the details, but if i close the form and reopen it again, i end up with this error.
IO Exception was unhandled
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\MyName\Documents\Visual Studio 2013\Projects\MyApp\MyApp\bin\Debug\pic0jpg' because it is being used by another process."
I've tried putting the filestream object in a using statement and other solutions but the error still exists. Any help would be appreciated, thanks.
public void loadPlane()
{
//convert picture to jpg and load other details
MySqlDataAdapter sqladapt;
DataSet dataSet;
DatabaseConnector dbcon = new DatabaseConnector();
dbcon.OpenConnection();
sqladapt = new MySqlDataAdapter();
sqladapt.SelectCommand = dbcon.InitSqlCommand("SELECT * FROM plane");
dataSet = new DataSet("dst");
sqladapt.Fill(dataSet);
dbcon.CloseConnection();
DataTable tableData = dataSet.Tables[0];
//use from iplane class
IPlane.countPlane = tableData.Rows.Count;
for (int i = 0; i < IPlane.countPlane; i++)
{
IPlane.planeObj[i] = new NormalPlane();
DataRow drow = tableData.Rows[i];
string plName = "pic" + Convert.ToString(i);
FileStream FSNew = new FileStream(plName+"jpg",FileMode.Create);
byte[] blob = (byte[])drow[5];
FSNew.Write(blob,0,blob.Length);
FSNew.Close();
FSNew = null;
IPlane.planeObj[i].PlaneImage=(Image.FromFile(plName + "jpg"));
IPlane.planeObj[i].ModelNumber = drow[0].ToString();
IPlane.planeObj[i].EngineType = drow[1].ToString();
IPlane.planeObj[i].FlySpeed = Convert.ToInt32( drow[2]);
IPlane.planeObj[i].SpecialFeature = drow[3].ToString();
IPlane.planeObj[i].Price = Convert.ToDouble( drow[4]);
IPlane.planeObj[i].EconSeats = Convert.ToInt32(drow[6]);
IPlane.planeObj[i].BussSeats = Convert.ToInt32(drow[7]);
IPlane.planeObj[i].FirstSeats = Convert.ToInt32(drow[8]);
//drow 5 is the image
}
}
this is the main problem:
IPlane.planeObj[i].PlaneImage=(Image.FromFile(plName + "jpg"));
you are opening the image and leaving it opened.
You have 2 way to go:
IPlane.planeObj[i].PlaneImage
and load the file when you need it. (I don't understad why you save an image as blob on db and then create the file anyway) If you don't have many image or they are not so big or you don't have memory problems I think the first is better.
by the way your code has a lots of resources not disposed (connection, streams, etc etc)