简体   繁体   中英

How do I store a image BLOB in an access database after getting the name from openfiledialog?

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.
       }

   }
}

我将使用File.ReeadAllBytes(file)并将byte []保存在数据库中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM