0

I have accessed a database which stores employee photos through a c# query. My question is: how can I save the photos to a regular file on my hard drive through a c# program? To create the file, I understand I will be using FileMode.Create and perhaps the SaveFileDialog class?

This is how I have read in the file:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}, {2}, {3}", reader["emp_id"], reader["first_name"], reader["last_name"], reader["photo"]));
            FileStream fs = new FileStream(SaveFileDialog.FileName, FileMode.Open); //something of this nature?
        }
    }
    finally
    {
        reader.Close();
    }
}

I have extracted necessary information from this SO question, but it doesn't really help me on saving the file. So, I am asking for some assistance on how to go about saving a binary file, which is a picture, that I want to save on my computer.

2
  • What database? What is the datatype of the column containing the image data? Commented Jun 16, 2016 at 16:22
  • @alex It is a Microsoft Database. And the column is a binary string. Commented Jun 16, 2016 at 16:45

1 Answer 1

3

File.WriteAllBytes will write bytes to a file of a given name.

In full, something like

File.WriteAllBytes(fileName, (byte[])reader["photo"]);

You can use a save file dialog to save the files, yes. But that's really more a question of your UX design (and application design). In general, loops and dialogs don't play very well - if you make me select 10 different file names to save photos with names you could choose yourself, I'm going to be angry at you :P

Sign up to request clarification or add additional context in comments.

1 Comment

Haha thank you for the response! I think I will just concatenate some strings for the file name variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.