当我保存图像c#windows应用程序时,空路径名称是不合法的

时间:2016-11-26 16:47:18

标签: c#

当我保存所有2张图片时,我想保存多张图片我也不例外... 但当我尝试只保存1或2或其抛出异常时#34;空路径不合法"。 我的代码在这里

  byte[] img = null;
  FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
  BinaryReader br = new BinaryReader(fs);
  img = br.ReadBytes((int)fs.Length);

  //

  byte[] img1 = null;
  FileStream fs1 = new FileStream(imgloc1, FileMode.Open, FileAccess.Read);
  BinaryReader br1 = new BinaryReader(fs1);
  img1 = br1.ReadBytes((int)fs1.Length);


  //
  con.Open();
  SqlCommand cmd1 = new SqlCommand("insert into easypaisa (trid,selectopt,smobile,rmobile,snic,rnic,tamount,tcharges,totalcharges,date,descr,inv_no,Company,user_name,sprof,dataimg,image2) values ('" + textBox1.Text + "','" + comboBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + dateTimePicker1.Value.ToString("MM-dd-yyyy") + "','" + textBox10.Text + "','" + textBox9.Text + "','" + comboBox2.Text + "','" + Get_User_label.Text + "','" + textBox13.Text + "',@dataimg,@image2)", con);
  cmd1.Parameters.Add(new SqlParameter("@dataimg", img));
  cmd1.Parameters.Add(new SqlParameter("@image2", img1));
  cmd1.ExecuteNonQuery();
  con.Close();

  MessageBox.Show("Data Saved successfully", "Important Message",
                   MessageBoxButtons.OK, MessageBoxIcon.Information);

1 个答案:

答案 0 :(得分:0)

在读取文件之前添加文件路径验证

  byte[] img = null;
  if(!String.IsNullOrEmpty(imgloc){
     FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
     BinaryReader br = new BinaryReader(fs);
    img = br.ReadBytes((int)fs.Length);
  }


  byte[] img1 = null;
  if(!String.IsNullOrEmpty(imgloc1){
     FileStream fs1 = new FileStream(imgloc1, FileMode.Open, FileAccess.Read);
     BinaryReader br1 = new BinaryReader(fs1);
     img1 = br1.ReadBytes((int)fs1.Length);
  }

还为图像参数设置DBNull值,因为现在它们可以为null

cmd1.Parameters.Add(new SqlParameter("@dataimg", img?? DBNull.Value));
cmd1.Parameters.Add(new SqlParameter("@image2", img1?? DBNull.Value));