简体   繁体   中英

How to save a binary file accessed from a database in C#?

I have accessed a database which stores employee photos through ac# query. My question is: how can I save the photos to a regular file on my hard drive through ac# 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM