0

我的问题与 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 个字节。

4

1 回答 1

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; 
    } 
于 2013-02-07T01:16:49.393 回答