c#存储图像到sql多选择

问题描述:

我想存储图像到sql使用c#应用程序。所以我有这个代码,并且多个选择是真的。我知道我需要使用数组文件名。你能帮我实现吗?我只需要在文件夹中选择多个文件并将其存储在SQL数据库中。c#存储图像到sql多选择

浏览图片:

private void btnBrowseImage_Click(object sender, EventArgs e) 
     { 
      OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
      openFileDialog1.Multiselect = true; 
      openFileDialog1.Title = "Sekili sec"; 

      openFileDialog1.InitialDirectory = "E:\\IKA"; 
      openFileDialog1.Filter = "All files (*.jpg)|*.jpg"; 
      // openFileDialog1.FilterIndex = 10; 
      openFileDialog1.RestoreDirectory = true; 

if (openFileDialog1.ShowDialog() == DialogResult.OK) 
      { 
       try 
       { 
        txtImagePath.Text = openFileDialog1.FileName; 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
       } 
      } 
     } 

文件二进制

byte[] ReadImageToBytes(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); 

      data = br.ReadBytes((int)numBytes); 
      return data; 
     } 

它们保存在SQL:

private void btnSave_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       //Read Image Bytes into a byte array 
       byte[] imageSampleData = ReadImageToBytes(txtImagePath.Text); 

       //Initialize SQL Server Connection 
      // SqlConnection con = new SqlConnection(txtConnectionString.Text); 

       String strConnString = "Data Source=1.1.1.1;Initial Catalog=Test1;User Id=dffr;Password=dffr;"; 
       SqlConnection con = new SqlConnection(strConnString); 
       //Set insert query 
       string query = "INSERT INTO tblImages (FullPath,MyImageSample) values(@FullPath, @MyImageSample)"; 

       //Initialize SqlCommand object for insert. 
       SqlCommand cmd = new SqlCommand(query, con); 

       cmd.Parameters.Add(new SqlParameter("@FullPath", 
              (object)txtImagePath.Text)); 

       cmd.Parameters.Add(new SqlParameter("@MyImageSample", 
                (object)imageSampleData)); 

       //Open connection and execute insert query. 
       con.Open(); 
       cmd.ExecuteNonQuery(); 
       con.Close(); 


      } 
      catch 
      { 
       MessageBox.Show("Error while saving image.", "Error"); 
      } 
     } 

您需要使用FileNames属性来获取选定文件的列表。

foreach(string filename in openFileDialog1.FileNames) 
{ 
    //1. read file 
    //2. store content of file into database. 
} 
+0

什么应该在循环的身体? – Delphi 2012-02-28 06:17:46

+0

它给我一个错误“'openFileDialog1'在当前上下文中不存在”。 – Delphi 2012-02-28 06:26:26