hi there,

I need to upload files to the mdf file in visual studio 2008 standard edition. the database table which takes the file data in to varchar datatype. i convert the data to byte and then save it in a varchar type field.

the code is below for uploading the file data to the mdf file.

try
            {

                string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\awaduge\My Documents\Visual Studio 2008\Projects\FileUploadDelete\FileUploadDelete\FileUploadDelete.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
                db.openConnection();
                using (SqlConnection con = new SqlConnection(constr))
                {

                    con.Open();
                    string path = @"C:\Documents and Settings\awaduge\Desktop\Code dgv subcontractor.docx";

                    byte[] bytearr = File.ReadAllBytes(path);
                    string query = @"Insert into files(filen) values(@file1)";

                    using (SqlCommand command = new SqlCommand(query, DB.getConnection()))
                    {
                        command.Parameters.Add(new SqlParameter("@file1", bytearr));
                        command.ExecuteNonQuery();
                    }
                }
                db.closeConnection();
                MessageBox.Show("Successfully aadded");
            }
            catch (Exception ex)
            {
                throw ex;
            }

but when i get try to get the data in to a msg box there is an error in the code i wrote with, which is shown below

String query = "Select filen From files Where id=1";
            SqlCommand command = new SqlCommand(query,DB.getConnection());
            
            db.openConnection();
            SqlDataReader reader = command.ExecuteReader();
            byte[] bytearr;

            while (reader.Read())
            {
                String a = reader.GetString(0);
                for (int i = 0; i < 50; i++)
                {
                    bytearr[i] = BitConverter.GetBytes(bool.Parse(a));
                }
               // byte[] bytearr = File.ReadAllBytes(a);
                MessageBox.Show(bytearr.ToString());
            }
           
            db.closeConnection();

how can i modify the above code so that i can view the data of the file that i have uploaded.

thankxxxxxx
appriciate if someone could help me in this

thnaxx in advance

This statement BitConverter.GetBytes(bool.Parse(a)); is parsing the complete file (held in a) to a single bool and then converting the bool to a byte array!
Is this what you intended? If not what did you expect to happen?
Perhaps what you need is

bytearr = (byte[])reader.GetValue(0);

This statement BitConverter.GetBytes(bool.Parse(a)); is parsing the complete file (held in a) to a single bool and then converting the bool to a byte array!
Is this what you intended? If not what did you expect to happen?
Perhaps what you need is

bytearr = (byte[])reader.GetValue(0);

hey don't want

"This statement BitConverter.GetBytes(bool.Parse(a)); is parsing the complete file (held in a) to a single bool and then converting the bool to a byte array! "
this

but i want to get the values each one and get the original data displayed in to a word document.

how can i do this??

i used the code that u gave me, but it says "use of unassinged local variable bytearr" why is that??

String query = "Select filen From files Where id=5";
            SqlCommand command = new SqlCommand(query,DB.getConnection());
            
            db.openConnection();
            SqlDataReader reader = command.ExecuteReader();
            

            while (reader.Read())
            {byte[] bytearr;
                String a = reader.GetString(0);
                for (int i = 0; i < 50; i++)
                {
                    bytearr = (byte[])reader.GetValue(0);
                }
                MessageBox.Show(bytearr.ToString());
            }
           
            db.closeConnection();

thankssss

You do not need the for loop. GetValue is retuning the complete byte array originally stored in the DB.

FYI the "use of unassinged local variable" error is because bytearr might not have a value by the time the code reaches the MessageBox statement (the assignment within the for loop does not count as it is conditional).

You do not need the for loop. GetValue is retuning the complete byte array originally stored in the DB.

FYI the "use of unassinged local variable" error is because bytearr might not have a value by the time the code reaches the MessageBox statement (the assignment within the for loop does not count as it is conditional).

hey when i run it it gives an exception with InvalidcastException was unhandleed Unable to cast object of type 'System.String' to type 'String.Byte[]'.

the code is below, the bolded line gives the error, i changed it to "byte.Parse(reader.GetValue(0))" but there is an exception as well, how can i avoid it???

String query = "Select filen From files Where id=5";
            SqlCommand command = new SqlCommand(query,DB.getConnection());
            
            db.openConnection();
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {byte[] bytearr;
                
               [B] bytearr = (byte[])reader.GetValue(0);[/B]
                MessageBox.Show(bytearr.ToString());
            }
           
            db.closeConnection();

thankxxxx

This is a type conflict with the data from the DB.
What type is filen in your DB.
To store byte[] it needs to be varbinary(MAX).
To store large strings is needs to be nvarchar(MAX).

This is a type conflict with the data from the DB.
What type is filen in your DB.
To store byte[] it needs to be varbinary(MAX).
To store large strings is needs to be nvarchar(MAX).

hye when i add filen to varbinary max and ten add data to the database, it saves as <Binary Date> in the filen field.,

and wen i get the data it displays in the database as System.Byte[]

hey the code is below, how can i do this???

thankxx in advance

the code is below

private void button1_Click(object sender, EventArgs e)
        {
            //code to insert data to the database
            try
            {

                string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\awaduge\My Documents\Visual Studio 2008\Projects\FileUploadDelete\FileUploadDelete\FileUploadDelete.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
                db.openConnection();
                using (SqlConnection con = new SqlConnection(constr))
                {

                    con.Open();
                    string path = @"C:\Documents and Settings\awaduge\Desktop\Code dgv subcontractor.docx";

                    byte[] bytearr = File.ReadAllBytes(path);
                    string query = @"Insert into files(filen) values(@file1)";

                    using (SqlCommand command = new SqlCommand(query, DB.getConnection()))
                    {
                        command.Parameters.Add(new SqlParameter("@file1", bytearr));
                        command.ExecuteNonQuery();
                    }
                }
                db.closeConnection();
                MessageBox.Show("Successfully aadded");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // code to retrieve data from the database
            String query = "Select filen From files Where id=7";
            SqlCommand command = new SqlCommand(query,DB.getConnection());
            
            db.openConnection();
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {byte[] bytearr;
                
                bytearr = (byte[])reader.GetValue(0);
                MessageBox.Show(bytearr.ToString());
            }
           
            db.closeConnection();
        }

This bit of code MessageBox.Show(bytearr.ToString()); is asking bytearr to convert itself to a string. An array has no knowledge of how to interpret the data it contains so the default ToString() operation on an array (or class) is to return the type name; whence "System.Byte[]" in your message box.

To show the contents of the byte array you will have to write some code that interprets the data contained in the array.

The file you are storing is a .docx. What did you hope would be displayed in the messagebox?

This bit of code MessageBox.Show(bytearr.ToString()); is asking bytearr to convert itself to a string. An array has no knowledge of how to interpret the data it contains so the default ToString() operation on an array (or class) is to return the type name; whence "System.Byte[]" in your message box.

To show the contents of the byte array you will have to write some code that interprets the data contained in the array.

The file you are storing is a .docx. What did you hope would be displayed in the messagebox?

hope to get the data in the doc file

thanxxx

This bit of code MessageBox.Show(bytearr.ToString()); is asking bytearr to convert itself to a string. An array has no knowledge of how to interpret the data it contains so the default ToString() operation on an array (or class) is to return the type name; whence "System.Byte[]" in your message box.

To show the contents of the byte array you will have to write some code that interprets the data contained in the array.

The file you are storing is a .docx. What did you hope would be displayed in the messagebox?

what i want is to get the data in the doc file but when i wrote the code numbers displayed, but in the doc file i have string values

the code is below

// code to retrieve data from the database
            String query = "Select filen From files Where id=7";
            SqlCommand command = new SqlCommand(query,DB.getConnection());
            
            db.openConnection();
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                byte[] bytearr;
                bytearr = (byte[])reader.GetValue(0);
                for (int i = 0; i < bytearr.Length;i++)
                    MessageBox.Show(bytearr[i].ToString());
            }
           
            db.closeConnection();

OK. Not sure quite what you expeced. After all, a byte is just a number from 0 to 255!.

Also, the .docx file is a Microsoft Office Open XML Format Document file. As far as I am aware the text and formating are managed using XML tagging, however, the docx file is still stored in a binary format.

Try opening the file in Notepad or Wordpad and see what you get. I expect it looks like garbage.

If I am wrong and the file is an ASCII based human readable document, then you need to make a few changes to your code to read and store the file as a string.

1) Modify the database field to receive the string data type (nvarchar(MAX) is probably best).

2) Read the file using File.ReadAllText to a string

3) Modify insert command to use a parameter and add the file using an SqlParameter to avoid problems with spaces etc.

4) Use GetString(0) to get the text from the SqlDataReader.

You now have a single large string with multiple lines of text in it.

Manipulate the string how you like.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.