Click here to Skip to main content
15,889,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How to Save file in sql database in c# win. form? Is it stored in bytes? Can somebody provide a code snipet as i searched through google and was not able to find a good article for this.

Thanks in advance
Posted

Generally you work with arrays of bytes, i found and example here: http://www.akadia.com/services/dotnet_read_write_blob.html[^]
 
Share this answer
 
Comments
agent_kruger 1-Mar-14 4:37am    
+5, nice article sir but can you provide the code sir which actually saves the file in sql database.
 
Share this answer
 
Comments
agent_kruger 1-Mar-14 6:42am    
+5, exactly what i needed.
Yes...It is stored in Bytes....here is the sample code...

C#
protected void Upload(object sender, EventArgs e)
{
    string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
    string contentType = FileUpload1.PostedFile.ContentType;
    using (Stream fs = FileUpload1.PostedFile.InputStream)
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            byte[] bytes = br.ReadBytes((Int32)fs.Length);
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "insert into tblFiles values (@Name, @ContentType, @Data)";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Name", filename);
                    cmd.Parameters.AddWithValue("@ContentType", contentType);
                    cmd.Parameters.AddWithValue("@Data", bytes);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}
 
Share this answer
 
Comments
agent_kruger 1-Mar-14 4:34am    
what is "FileUpload1"?
agent_kruger 1-Mar-14 4:36am    
sir, i think this works for web but i need it for desktop application "Windows Application"
Pranav-BiTwiser 1-Mar-14 4:42am    
sorry,, i thought you want code in web based...but fileupload1 is a ID of fileupload control in asp.net

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