【问题标题】:Save binary image to SQL-CE in C#在 C# 中将二进制图像保存到 SQL-CE
【发布时间】:2013-05-27 16:39:27
【问题描述】:

我有一个名为 Recipe 的 SQL-CE 表,该表中有 4 列 ID(int)、Name(nvarchar)、Instructions(nvarchar) 和 image(binary)。

这是 UI 的样子:

当您单击“添加新”按钮时,我希望用户输入名称、说明,然后单击“添加图像”按钮并选择图像。然后,我希望包含文本“内存中没有图像”的标签更改为“内存中的图像”,以表示图像正在等待写入数据库。最后,当用户单击“保存”图标时,我希望保存 3 个 nvarchar 字段,以及以二进制形式写入表中的图像。

代码如下:

添加图片按钮

private void button1_Click(object sender, EventArgs e)
        {
            int size = -1;
            DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
                string file = openFileDialog1.FileName;
                try
                {
                    string text = File.ReadAllText(file);
                    size = text.Length;
                }
                catch (IOException)
                {
                }
            }


        }

保存图标

 private void recipeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.recipeBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.recipeDataSet);
            MessageBox.Show("Recipe Saved!", "Save Item");

        }

最后我希望数据库中保存的每个对应图像都显示在图片框中的“添加图像”按钮下方,因此需要将其从二进制格式转换回以显示图像。

我的问题

通过调出 OpenFileDialog 选择文件后,如何更改 'No image in memory' 标签以显示 'Image in memory' 屏幕。然后我需要添加什么代码才能使保存按钮单击事件将图像作为二进制文件写入我的 SQL-CE db。

【问题讨论】:

  • @Otiel 对不起,我已经在底部总结了我现在需要完成的事情。

标签: c# .net sql sql-server-ce


【解决方案1】:

获得文件后,可以将其读入字节数组,然后将该数组复制到当前记录中的正确字段

类似的东西

OpenFileDialog openFileDialog = new OpenFileDialog();

// if the user selects a file
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
    // now open the file ..
    FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);

    // or you may use 
    // FileStream fs = (FileStream)openFileDialog.OpenFile();

    BinaryReader br = new BinaryReader(fs);
    Byte[] buffer = br.ReadBytes((Int32)fs.Length);
    br.Close();
    fs.Close();
}

// now copy content of 'buffer' to the correct filed of the recordset

要更改标签,您应该能够通过订阅正确的 BindingSource 事件 (CurrentItemChanged 如果我没记错的话)

【讨论】:

  • 用什么代替 yourFilePath?用户将使用 openfiledialog 从他们的本地计算机中选择文件,所以我希望文件路径是 autp 填充的?
  • 你是对的.. 用通过 OpenFileDialog 收集的路径+文件名替换 yourFilePath - cm
  • 抱歉,但代码是什么,因为我以前没有使用过 OpenFileDialog。谢谢
  • 嗨,SelectDistinct,我为您修改了代码.. 试一试@it.. 请注意,在进行修改时我没有 VS,因此您必须检查语法的准确性.关于 OpenFileDialog msdn.microsoft.com/en-au/library/… 的一个很好的参考 - 希望这会帮助你 .. 快乐编码
猜你喜欢
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 2015-01-08
  • 2016-07-12
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2015-08-13
相关资源
最近更新 更多