读取SQL Server IMAGE 类型字段生成实体文件

来源:互联网 发布:mac没有flash怎么办 编辑:程序博客网 时间:2024/06/07 05:54

前几天,需要弄个工具把数据库中的IMAGE字段读出生成实体文件。居然弄了10+分钟,郁闷。特此留下标记,对自己以示警告:

using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Data.SqlClient;namespace ConsoleApp{    class Program    {        static void Main(string[] args)        {            SqlConnection conn = new SqlConnection("myConnectionString");            conn.Open();            SqlCommand command = new SqlCommand("myCommandText", conn);            SqlDataReader reader = command.ExecuteReader();            while (reader.Read())            {                byte[] writer = (byte[])reader["imageColumn"];                string fileDir = @"myImageDir";                if (!Directory.Exists(fileDir))                    Directory.CreateDirectory(fileDir);                using (FileStream fos = new FileStream(                    string.Format(@"{0}\{1}.jpg", fileDir, reader["imageName"].ToString()),                     FileMode.OpenOrCreate, FileAccess.ReadWrite))                {                    fos.Write(writer, 0, writer.Length);                    fos.Close();                }            }            reader.Dispose();            command.Dispose();            conn.Close();        }    }}