简体   繁体   English

上传文件并保存到数据库

[英]Upload File and Save to Database

I am trying to upload a file from disk and then insert the file into a varbinary db column. 我正在尝试从磁盘上传文件,然后将文件插入varbinary db列。

I can't seem to figure out how to insert the binary file. 我似乎无法弄清楚如何插入二进制文件。

I am using C# and Linq to Sql in a WPF application. 我在WPF应用程序中使用C#和Linq到Sql。

Here is what I am trying so far! 到目前为止,这是我正在尝试的! Any suggestions or advice would be appreciated. 任何建议或意见将不胜感激。

private void UploadFile()
        {
            DatabaseData.DataClassesDataContext context = new DatabaseData.DataClassesDataContext();
            {
            OpenFileDialog dlgOpen = new OpenFileDialog();
            dlgOpen.Title = "Select file";

            FileData fd = new FileData();
            if (dlgOpen.ShowDialog() ?? false)
            {
                FileStream inStream = File.OpenRead(dlgOpen.FileName);
                //FileStream outStream = File.OpenWrite(dlgOpen.FileName + ".xlsx");
                int b;

                while ((b = inStream.ReadByte()) > -1)
                    // outStream.WriteByte((byte)b);


                    fd.FileId = Guid.NewGuid();
                    //fd.DataFile = inStream;//DataFile is the Varbinary column in the db
                    fd.Title = dlgOpen.FileName;
                    fd.FileExtension = txtExtension.text;

                    context.FileDatas.InsertOnSubmit(fd);
                    context.SubmitChanges();

                    //outStream.Flush();
                    //outStream.Close();
                    inStream.Close();
            }
            }
        }

To fix the compile error, remove the while statement. 要解决编译错误,请删除while语句。 You're trying to create a new FileData() which can never be used until b > -1 . 您正在尝试创建一个新的FileData(),直到b > -1时才可以使用。

I don't know that the code will work after that, but it will fix this one compile error. 我不知道代码在那之后会起作用,但是它将解决这一编译错误。

private void UploadFile()
{
    DatabaseData.DataClassesDataContext context = new DatabaseData.DataClassesDataContext();
    {
        OpenFileDialog dlgOpen = new OpenFileDialog();
        dlgOpen.Title = "Select file";

        if (dlgOpen.ShowDialog() ?? false)
        {
            FileStream inStream = File.OpenRead(dlgOpen.FileName);

            FileData fd = new FileData();
            fd.FileId = Guid.NewGuid();
            fd.DataFile = inStream;
            fd.Title = dlgOpen.FileName;
            fd.FileExtension = txtExtension.text;

            context.FileDatas.InsertOnSubmit(fd);
            context.SubmitChanges();

            inStream.Close();
        }
    }
}

Not sure if this will work, but try this 不知道这是否行得通,但是尝试一下

 if (dlgOpen.ShowDialog() ?? false)
                    {
                        byte[] bytes = System.IO.File.ReadAllBytes(dlgOpen.FileName);

                            fd.FileId = Guid.NewGuid();
                            fd.DataFile = bytes;
                            fd.Title = dlgOpen.FileName;                   
                            context.FileDatas.InsertOnSubmit(fd);
                            context.SubmitChanges();

Well, you read my disclaimer in your comments. 好吧,您在评论中读了我的免责声明。 I can't guarantee any pros here would agree with the approach it's per your request. 我不能保证这里的任何专家都会同意您所要求的方法。 I am just learning C# the right way and got the idea to convert a working non-database program. 我只是在以正确的方式学习C#,并且有了转换非数据库程序的想法。 I needed this to convert all my existing data into a new database that was to take over storage: 我需要将所有现有数据转换为新的数据库来接管存储:

/* Spawned from a button click
...
*/
        //
        // Here I bring in the directory which you'll likely replace with
        // a single file
        //
        string[] files = 
            Directory.GetFiles( 
            @"yourDicectory");

            // 
            // At this point you may disregard my loop if needed
            //
            foreach (string file in files)
            {
                //
                // Here the entire files are read and split
                // Handle your data how you like
                //  
                StreamReader fileReader = new StreamReader( file );
                string lines = fileReader.ReadToEnd();
                string[] entries = lines.Split( ',' );

                // 
                // Here, omitted, I declare variables of types to insert "holders" 
                // Every CSV has to go to a corresponding holder of the 
                // the appropriate type (i.e., DateTime, decimal(money), or yourType)
                //

                SqlCeConnection con = new SqlCeConnection( "Data Source = YourDataSource.sdf" );
                con.Open();
                SqlCeCommand cmd  = con.CreateCommand();

                //
                // The insert command that takes the parsed values - value1, value2, ...
                // which are the named and omitted declarations from above
                // You're providing a signature of the table you're inserting into
                // 
                cmd.CommandText = "INSERT INTO YourTable ([Column1], [Column2], [Column3], ... , [Column(n)]) VALUES (value1, value2, value3, ... , value(n))";

                //
                // Here, omitted, I parse and convert the values and store them in the holders
                //

                // Now execute and catch if needed
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch( SqlCeException sqle )
                    {
                        myTextbox.Text += sqle.Errors.ToString() + "\n";
                    }
                }
                //
                // Update my view - May not apply
                //
                myGridView1.Update();
                con.Close();
            }
/* Do whatever else you'd like ... */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 上载新文件首先检查此文件在数据库中是否已经存在,然后不存在将其保存在数据库中 - upload new file first check if this file exist already in database or not then if not exist save that in database 从客户端计算机读取数据并将其保存到数据库,而无需保存文件或将其上传到服务器 - Read data from clients machine and save it to database without needing to save the file or upload it to the server 上传文件并以二进制形式保存在文件夹中或数据库中 - Upload files and save in folder or save in database as binary 将文本文件上传到数据库 - Upload text file to database 用户在编辑视图中单击保存按钮后,如何将文件上传到文件系统并将路径保存到数据库? - How do I upload file to file system and save path to database AFTER user clicks save button in Edit view? 如何使用MVC中的Rest Sharp Web API在数据库和文件夹中保存和上传文件? - How to Save and Upload File in Database and Folder Using Rest Sharp Web API in MVC? aspx c#在上传之前重命名文件中的问题并使用数据库保存到名称 - problem in aspx c# rename file before upload and save to name with database 将DataTable作为文件保存到数据库 - Save DataTable to database as a file MySQL将文件保存到数据库 - MySQL Save File to Database 文件未保存在数据库中 - file not save in database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM