简体   繁体   English

如何在C#中保存从数据库访问的二进制文件?

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

I have accessed a database which stores employee photos through ac# query. 我已经访问了一个通过ac#查询存储员工照片的数据库。 My question is: how can I save the photos to a regular file on my hard drive through ac# program? 我的问题是:如何通过ac#程序将照片保存到硬盘上的常规文件中? To create the file, I understand I will be using FileMode.Create and perhaps the SaveFileDialog class? 要创建文件,我知道我将使用FileMode.Create以及SaveFileDialog类?

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问题中提取了必要的信息,但是对保存文件并没有真正的帮助。 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. File.WriteAllBytes将字节写入给定名称的文件。

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). 但这实际上是您的UX设计(和应用程序设计)的问题。 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 通常,循环和对话框的播放效果不是很好-如果您让我选择10个不同的文件名来保存可以选择的名称的照片,我会很生您的气:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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