Save images to local disk from a database

Posted on 2007-08-05
Last Modified: 2013-11-05
Dear Experts,
I have a table containing employees information like Employee ID and Employee Photo
I need to get all the employees photos which stored in a binary filelds in the database and save them to my local hard disk, each photo should take the name of the Employee ID.
am using C# in my ASP.NET Project
thanks ..
Question by:eghanem
    1 Comment
    LVL 18

    Accepted Solution

    So what is your question?  Do you need help retrieving the data, or saving it to a file, or both?

    Here's some information on this:

    private void retrieveImages()
            byte[] EmpImage;
            int EmpID;
            FileStream fs;

            // replace _CONNECTION_STRING_ with your own.
            SqlConnection MyConnection = new SqlConnection(_CONNECTION_STRING_);

            // replace query with your own
            SqlCommand MyCommand = new SqlCommand("SELECT emp_id, emp_img FROM employee", MyConnection);

            SqlReader MyReader = MyCommand.ExecuteReader()

            // loop through all the records and save the images
            while (MyReader.Read())
                EmpId = (int) MyReader["emp_id"];
                EmpImage = (byte[]) MyReader["emp_img"];

                // change the extension to the appropriate one
                fs = new FileStream(EmpId.ToString + '.jpg', FileMode.CreateNew, FileAccess.Write);
                fs.Write(EmpImage, 0, EmpImage.Length);


        catch(Exception ex)
            // handle exceptions

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on could not pull conte…
    Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
    This video discusses moving either the default database or any database to a new volume.
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    730 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now