Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to upload a file from disk and then insert the file into a varbinary db column.

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.

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();
            }
            }
        }
share|improve this question
2  
Does that even compile? I would've thought that a varbinary column would be represented by an array/collection of bytes in code, not a stream! –  appclay Jun 7 at 3:24
1  
No, when I start the inserts it fails. –  UserRegistration Jun 7 at 3:26
2  
Fails how? Without more information we'd have to replicate your database and DBML, which fewer people are willing to do. –  TheEvilPenguin Jun 7 at 3:27
1  
Embedded statement cannot be a declaration or labeled statement. FileData fd = new FileData(); Im trying to take it out of the IF! –  UserRegistration Jun 7 at 3:37
1  
If you like I can post code I just wrote that reads from a collection of files and inserts CS Values into a database. They're text files and the values are being converted to date and money types. Not sure if it'll help. –  BobbyDigital Jun 7 at 4:11
show 1 more comments

4 Answers

up vote 1 down vote accepted

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();
share|improve this answer

To fix the compile error, remove the while statement. You're trying to create a new FileData() which can never be used until 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();
        }
    }
}
share|improve this answer

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. 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 ... */
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.