难以将名称保存到SQL Server的图像路径

时间:2018-05-18 16:14:28

标签: c# sql-server

我有一个应用程序将图像保存到文件夹,将路径文件夹保存到SQL Server数据库。我能够将图像保存到文件夹,但SQL Server表中的列仅将路径保存为C:\Images,而不附加图像的图像名称。示例:我想将C:\Images\cat.jpg存储在表列中。

任何建议都会有所帮助。

我已将此声明为全局变量:

string displayimg, filePath,location;
string folderpath = @"C:\Images";
OpenFileDialog open = new OpenFileDialog();

此代码打开图片框:

private void button2_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();
    // image filters  
    open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

    if (open.ShowDialog() == DialogResult.OK)
    {
        // display image in picture box  
        displayimg = open.SafeFileName;
        pictureBox1.Image = new Bitmap(open.FileName);

        txtpath.Text = open.FileName;
        filePath = open.FileName;
        location = open.FileName;
    }
}

以下是保存代码:

private void button1_Click(object sender, EventArgs e)
{
    cn.Open();

    cmd = new SqlCommand("INSERT INTO jimmy (Id, FirstName, LastName, Telephone, Address, City, Country, Image ) VALUES (@Id, @FirstName, @LastName, @Telephone, @Address, @City, @Country, @Image)", cn);

    cmd.Parameters.AddWithValue("@Id", lblID.Text);
    cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text);
    cmd.Parameters.AddWithValue("@LastName", txtlastname.Text);
    cmd.Parameters.AddWithValue("@Telephone", txttelephone.Text);
    cmd.Parameters.AddWithValue("@Address", txtaddress.Text);
    cmd.Parameters.AddWithValue("@City", txtcity.Text);
    cmd.Parameters.AddWithValue("@Country", txtcountry.Text);
    // saves images path and name to table
    cmd.Parameters.AddWithValue("@Image", folderpath + Path.GetFileName(open.FileName));

    cmd.ExecuteNonQuery();
    cn.Close();

    MessageBox.Show("Saved");

    //saves images to folder
    File.Copy(filePath, Path.Combine(folderpath, Path.GetFileName(filePath)), true);
    cleartext();
    cn.Close();
}

2 个答案:

答案 0 :(得分:2)

我认为你的问题是你已经在全局和button2_Click方法的范围内声明了。 filePath被设置为button2_Click方法中所需的值。所以在button2_Click中删除open的声明,并在button1_Click方法中更改

  

folderpath + Path.GetFileName(open.FileName)

  

filePath

这就是为什么全球性应该非常谨慎地使用。理想情况下,您可以调用一个方法,这些值将被返回,存储并传递给另一个方法。

答案 1 :(得分:0)

更改此行

cmd.Parameters.AddWithValue("@Image", folderpath + Path.GetFileName(open.FileName));

要...

cmd.Parameters.Add(new SqlParameter("image", SqlDbType.VarChar) { Value = Path.Combine(folderpath,Path.GetFileName(open.FileName)) });