我正在构建一个winform应用程序,用于将文件存档到数据库中。 为了选择文件我使用下面的代码:
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = true;
dlg.Filter ="Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
DialogResult dlgRes = dlg.ShowDialog();
if (dlgRes == DialogResult.OK)
{
foreach (String file in dlg.FileNames)
{
// Create a PictureBox.
try
{
Label name= new Label();
Label fullpath = new Label ();
Label ext= new Label();
name.Text = Path.GetFileName(file);
fullpath.Text = file;
ext.Text = Path.GetExtension(name.Text);
flpName.Controls.Add(name);
flpFullPath.Controls.Add(fullpath);
flpExt.Controls.Add(ext);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
为了插入数据库,我使用了这段代码:
foreach (Control f in flpFullPath.Controls)
{
//try
//{
//Read File Bytes into a byte array
byte[] FileData = ReadFile(f.Text);
string path = Path.GetFileName(f.Text);
//Set insert query
string qry = @"Insert into FilesStore (Linja, Magazina, Arkiva, OriginalPath,FileData,Lloji, Data,NrProt, EmriDok,Perdoruesi) values(@linja,@magazina,@arkiva,@OriginalPath, @FileData, @lloji, @Data,@nrprot, @emr,@perdoru)";
//Initialize SqlCommand object for insert.
SqlCommand SqlCom = new SqlCommand(qry, con);
DateTime dt = DateTime.Now; // Use current time
string format = "dd/MM/yyyy HH:mm:ss"; // modify the format depending upon input required in the column in database
// string insert = @" insert into Table(DateTime Column) values ('" + dt.ToString(format) + "')";
//We are passing Original File Path and File byte data as sql parameters.
SqlCom.Parameters.Add(new SqlParameter("@linja", (object)cbLinja.Text));
SqlCom.Parameters.Add(new SqlParameter("@magazina", (object)cbDokMagazina.Text));
SqlCom.Parameters.Add(new SqlParameter("@arkiva", (object)cbArkiv.Text));
SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", (object)f.Text));
SqlCom.Parameters.Add(new SqlParameter("@FileData", (object)FileData));
SqlCom.Parameters.Add(new SqlParameter("@lloji", (object)cbLloji.Text));
SqlCom.Parameters.Add(new SqlParameter("@Data", (object)dt.ToString(format)));
SqlCom.Parameters.Add(new SqlParameter("@nrprot", (object)txtDocProt.Text));
SqlCom.Parameters.Add(new SqlParameter("@emr", (object)Path.GetFileNameWithoutExtension(path)));
SqlCom.Parameters.Add(new SqlParameter("@perdoru", (object)lblPerd.Text));
//Open connection and execute insert query.
con.Open();
SqlCom.ExecuteNonQuery();
con.Close();
}
我的问题在于插入代码。当我选择5张不同的图片时,代码只会将1张图片上传5次到数据库中。