Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone!
Can anyone tell me how I can create a table in SQL-Server and the final column contains a file with extension of pdf format??? :doh:

Thanks!
Posted
Updated 19-Dec-10 7:46am
v2
Comments
Manfred Rudolf Bihy 19-Dec-10 13:45pm    
What exactly do you mean by "... contain a file with extension of pdf format"? Should that column contain the file name or the file content of that pdf?
Manfred Rudolf Bihy 19-Dec-10 13:46pm    
Minor spelling and grammar edits.

For storing the file, you can use varbinary(max) type in sql table. Then first you read file into a memory stream:
FileStream st = new FileStream(@"C:\pdfname.pdf", FileMode.Open);
            byte[] buffer = new byte[st.Length];
            st.Read(buffer, 0, (int)st.Length);
            st.Close();

then put that stream into byte array, and then insert the byte array to sql:
SqlConnection conn = new SqlConnection("...");
            SqlCommand cmd = new SqlCommand("UPDATE SomeTable SET pdf=@pdf WHERE ID = 1", conn);
            cmd.Parameters.AddWithValue("@pdf", buffer);
            conn.Open();
            int i = cmd.ExecuteNonQuery();
            conn.Close();


If you want to "remember" the file names, you should open up another column in the table for storing file names. For retrieving files, just do the reverse:
SqlConnection connection = new SqlConnection ("...");
        connection.Open ();
        SqlCommand command = new 
          SqlCommand ("select pdf from Table", connection);
        byte[] buffer = (byte[]) command.ExecuteScalar ();
        connection.Close();
        FileStream fs = new FileStream(@"C:\test.pdf", FileMode.Create);
        fs.Write(buffer, 0, buffer.Length);
        fs.Close();

If your file is too big to handle with integers, you should implement buffer mechanism;i.e. save bytes in manageable portions.
Examples for this and further information can be found here
 
Share this answer
 
Comments
donudi 25-Dec-10 15:04pm    
thank you so much it's helped me some kind .
If you want to store the entire PDF file, then you can use a BLOB or equivalent field.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900