如何保存从 C# 中的数据库访问的二进制文件?
How to save a binary file accessed from a database in C#?
我已经通过 C# 查询访问了一个存储员工照片的数据库。我的问题是:如何通过 C# 程序将照片保存到硬盘驱动器上的常规文件中?要创建文件,我知道我将使用 FileMode.Create
,也许 SaveFileDialog
class?
这是我在文件中读到的:
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();
}
}
我已经从 this SO question 中提取了必要的信息,但它并没有真正帮助我保存文件。因此,我正在寻求有关如何保存二进制文件(图片)的帮助,我想将其保存在我的计算机上。
File.WriteAllBytes
将字节写入给定名称的文件。
完整,类似
File.WriteAllBytes(fileName, (byte[])reader["photo"]);
您可以使用保存文件对话框来保存文件,是的。但这实际上更多是您的用户体验设计(和应用程序设计)的问题。一般来说,循环和对话框播放效果不是很好 - 如果你让我 select 10 个不同的文件名来保存照片,你可以自己选择名称,我会生你的气的:P
我已经通过 C# 查询访问了一个存储员工照片的数据库。我的问题是:如何通过 C# 程序将照片保存到硬盘驱动器上的常规文件中?要创建文件,我知道我将使用 FileMode.Create
,也许 SaveFileDialog
class?
这是我在文件中读到的:
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();
}
}
我已经从 this SO question 中提取了必要的信息,但它并没有真正帮助我保存文件。因此,我正在寻求有关如何保存二进制文件(图片)的帮助,我想将其保存在我的计算机上。
File.WriteAllBytes
将字节写入给定名称的文件。
完整,类似
File.WriteAllBytes(fileName, (byte[])reader["photo"]);
您可以使用保存文件对话框来保存文件,是的。但这实际上更多是您的用户体验设计(和应用程序设计)的问题。一般来说,循环和对话框播放效果不是很好 - 如果你让我 select 10 个不同的文件名来保存照片,你可以自己选择名称,我会生你的气的:P