如何将大文件存储到SQL Server 2008并检索所有文件?

时间:2013-02-06 18:57:32

标签: c# sql-server wpf sql-server-2008

我的问题与SQL Server数据库有关。

我使用以下代码成功地将数据存储到C#的SQL Server表中:

 internal static void SaveAutocadFileOnDataBase(string MapCode, byte[] dataElecMap, string dataElecMapName,byte[] dataCivilMap, string dataCivilMapName, byte[] dataArchiMap, string dataArchiMapName,byte[]dataMechaMap,string dataMechaMapName)
        {
            string sqlcommand = string.Concat("INSERT INTO AutoCadFiles VALUES ('", MapCode, "' , ", "cast ('", dataElecMap, "' as varbinary(max)),", " '", dataElecMapName, "' ", " , cast ('", dataCivilMap, "' as varbinary(max)) ,", " '", dataCivilMapName, "' ", " , cast ('", dataArchiMap, "' as varbinary(max)) ,", " '", dataArchiMapName, "' "," , cast ('", dataMechaMap, "' as varbinary(max)) ,", " '", dataMechaMapName, "' ", ")");  ExecuteNonQuery(sqlcommand);
        }

并使用此代码检索它:

    internal static DataTable RetriveMaps(string MapNumber, string MapType)
    {
        string s = MapType + "Name";
        string SqlCommand = string.Concat("SELECT ", MapType, " , ", s, " FROM AutoCadFiles WHERE MapCode='",MapNumber, "'");
        return GetBinaryFiles(SqlCommand);
    }

    private static DataTable GetBinaryFiles(string SqlCommand)
    {
        SqlConnection SqlConnction = null;
        DataTable dt = new DataTable();
        SqlCommand sqlcom = GetConnection(SqlCommand, ref  SqlConnction);
        SqlDataReader sdldr = sqlcom.ExecuteReader();
        dt.Load(sdldr);
        return dt;
    }

我成功从dataTable获取文件并将其保存到文件系统中。但存储的文件卷是0字节

或13字节远小于数据库中存储的文件。

1 个答案:

答案 0 :(得分:0)

由于您一次只检索一行,因此这个更简单的代码可用于检索数据:

        string fileName;
        byte[] fileread;

        SqlCommand command;
        SqlConnection connection = MyGetSqlConnection();

        connection.Open();

        command = new SqlCommand("Select dataElecMapName From AutoCadFiles  Where MapCode = @MapNumber", connection);
        command.Parameters.Add("@MapNumber", SqlDbType.Int).Value = MapNumber;
        fileName = (string)command.ExecuteScalar();
        command.Dispose();

        command = new SqlCommand("Select dataElecMap From AutoCadFiles  Where MapCode = @MapNumber", connection);
        command.Parameters.Add("@MapNumber", SqlDbType.Int).Value = MapNumber;

        fileread = (byte[])command.ExecuteScalar();

        string tempPath = MyFunc.GetTempDirectory();

        FileStream fs = new FileStream(tempPath + fileName, FileMode.Create);
        fs.Write(fileread, 0, fileread.Length);

        System.Diagnostics.Process.Start(tempPath + fileName);

        fs.Close();

修改 使用此代码转换您的文件:

    public static byte[] ConvertFileToBytes(string location, ref string FileName) 
    { 
        FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read);

        BinaryReader reader = new BinaryReader(fs);

        byte[] data = reader.ReadBytes((int)fs.Length);

        fs.Close(); 
        return data; 
    }