在数据库c#上插入多个文件

时间:2017-05-23 11:08:07

标签: c# winforms

我正在c#中创建一个 winform 应用程序,用于将文档,图像,视频等存档到SQL Server中。到目前为止,我已经能够从 opendialog 中选择文件,并将所选文档的路径保存到列表框中。这是代码:

    public void btnLoad_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Multiselect = true;
        dlg.Filter = "All files (*.*)|*.*";

        DialogResult dlgRes = dlg.ShowDialog();
        if (dlgRes == DialogResult.OK)
        {

            foreach (String file in dlg.FileNames)
            {

                listBox1.Items.Add(file);
            }
        }

    }

我现在要做的是向数据库插入在 OpenFileDialog 上选择的所有文档。 的修改 这是我将文件插入数据库的代码。

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

        //When you use BinaryReader, you need to supply number of bytes to read from file.
        //In this case we want to read entire file. So supplying total number of bytes.
        data = br.ReadBytes((int)numBytes);

        //Close BinaryReader
        br.Close();

        //Close FileStream
        fStream.Close();

        return data;
    }

    private void btnDocAdd_Click(object sender, EventArgs e)
    {

        var myOtherList = listBox1.Items.Cast<String>().ToList();

        foreach (var f in myOtherList)
        {

            byte[] FileData = ReadFile(f);
            string path = Path.GetFileName(f);
            //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));
            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));

            con.Open();

            SqlCom.ExecuteNonQuery();

            con.Close();

当我逐个添加文档时,它可以正常工作。但是当我尝试添加多个文档时,它只添加一个文档x次(x =列表框中的项目数)

2 个答案:

答案 0 :(得分:0)

以下不使用OpenDialog,而是简单地选择app调试文件夹下面的文件夹中的所有图像,这当然是硬编码的,但想法只是获取您通过OpenDialog执行的图像文件。把它想象成一个模拟。

表单代码(调用下面发现​​的类中的方法)在这里我填充文件,当插入图像时也获得新的主键,这是为了显示插入工作。在一个真实的应用程序中,我们将返回更改的列表,这里我不是。

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
            List<ImageItem> imageItemsList = (
                from file in Directory.GetFiles(location)
                select new ImageItem
                {
                        Name = Path.GetFileName(file),
                        Bytes = File.ReadAllBytes(file),
                        Description = "Inserted from code sample"
                    }
                ).ToList();

            DatabaseImageOperations ops = new DatabaseImageOperations();
            ops.InsertImages(imageItemsList);
        }
    }
}

数据操作类

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

public class DatabaseImageOperations
{
    private string databaseServer = @".\SQLEXPRESS";
    private string defaultCatalog = "ImageData1";
    private string _ConnectionString;
    private string ConnectionString
    {
        get
        {
            return _ConnectionString;
        }
        set
        {
            _ConnectionString = value;
        }
    }
    public DatabaseImageOperations()
    {
        _ConnectionString = $"Data Source={databaseServer};Initial Catalog={defaultCatalog};Integrated Security=True";
    }
    public void InsertImages(List<ImageItem> Images)
    {
        using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
        {
            using (SqlCommand cmd = new SqlCommand { Connection = cn })
            {
                cmd.CommandText = "INSERT INTO ImageData (ImageData, [Description]) " + 
                                  "VALUES  (@img, @description);SELECT CAST(scope_identity() AS int);";

                cmd.Parameters.Add("@img", SqlDbType.Image);
                cmd.Parameters.Add("@description", SqlDbType.Text);

                cmd.Parameters.Add(new SqlParameter
                {
                    ParameterName = "@new_identity",
                    SqlDbType = SqlDbType.Int,
                    Direction = ParameterDirection.Output
                });

                cn.Open();

                foreach (ImageItem item in Images)
                {
                    cmd.Parameters["@img"].Value = item.Bytes;
                    cmd.Parameters["@description"].Value = item.Description;
                    item.Id = Convert.ToInt32(cmd.ExecuteScalar());
                }
            }
        }
    }
}

存储文件信息的类。

public class ImageItem
{
    public int Id { get; set; }
    public byte[] Bytes { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }
}

表格结构

USE [ImageData1]
CREATE TABLE [dbo].[ImageData](
    [ImageID] [int] IDENTITY(1,1) NOT NULL,
    [ImageData] [image] NULL,
    [Description] [nvarchar](max) NULL,
 CONSTRAINT [PK_ImageData] PRIMARY KEY CLUSTERED 
(
    [ImageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

希望这有助于您明智地适应您的任务。 enter image description here

修改: 这是一个使用ListBox

的版本(仍然没有打开的对话框)
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
            List<ImageItem> imageItemsList = (
                from file in Directory.GetFiles(location)
                select new ImageItem
                {
                        Name = Path.GetFileName(file),
                        Bytes = File.ReadAllBytes(file),
                        Description = "Inserted from code sample"
                    }
                ).ToList();

            listBox1.DataSource = imageItemsList;
            listBox1.DisplayMember = "Name";

        }
        private void button2_Click(object sender, EventArgs e)
        {
             var imageItemsList = (List<ImageItem>)listBox1.DataSource;
            DatabaseImageOperations ops = new DatabaseImageOperations();
            ops.InsertImages(ref imageItemsList);
        }
    }
}

对数据类的小修改

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

public class DatabaseImageOperations
{
    private string databaseServer = @"L-36007\SQLEXPRESS";
    private string defaultCatalog = "ImageData1";
    private string _ConnectionString;
    private string ConnectionString
    {
        get
        {
            return _ConnectionString;
        }
        set
        {
            _ConnectionString = value;
        }
    }
    public DatabaseImageOperations()
    {
        _ConnectionString = $"Data Source={databaseServer};Initial Catalog={defaultCatalog};Integrated Security=True";
    }
    public void InsertImages(ref List<ImageItem> Images)
    {
        using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
        {
            using (SqlCommand cmd = new SqlCommand { Connection = cn })
            {
                cmd.CommandText = "INSERT INTO ImageData (ImageData, [Description]) " + 
                                  "VALUES  (@img, @description);SELECT CAST(scope_identity() AS int);";

                cmd.Parameters.Add("@img", SqlDbType.Image);
                cmd.Parameters.Add("@description", SqlDbType.Text);

                cmd.Parameters.Add(new SqlParameter
                {
                    ParameterName = "@new_identity",
                    SqlDbType = SqlDbType.Int,
                    Direction = ParameterDirection.Output
                });

                cn.Open();

                foreach (ImageItem item in Images)
                {
                    cmd.Parameters["@img"].Value = item.Bytes;
                    cmd.Parameters["@description"].Value = item.Description;
                    item.Id = Convert.ToInt32(cmd.ExecuteScalar());
                }
            }
        }
    }
}

enter image description here

答案 1 :(得分:-2)

您可以将所有路径保存在同一列中,并以逗号分隔,并在从DB中检索时将它们拆分为列表。

将所有路径加在一起:

var DBValue = string.Join(",", listBox1.Items.Cast<String>().ToList())

从DB中检索:

var ListofAttachments= DBValue.Split(',').ToList<string>();