locked
Storing and retrieving files from Sql server 2005 with C# RRS feed

  • Question

  • I am trying to store whole files in the SQL Server 2005.I am storing them as image files as this seems to stroing the file as binary data

    Created 

     

    Spreadsheet class

     

    private byte[] _rawFile = new byte[0];

    public Guid Id = Guid.Empty;

    public string FileName;

    public string ModifyBy;

    public Spreadsheet(string fileName)

    {

    FileName = fileName;

    }

    public byte[] RawFile

    {

    get

    {

    return _rawFile;

    }

    set

    {

    _rawFile = value;

    }

    }

    public byte[] UnCompressedFile

    {

    get

    {

    try

    {

    return Compressor.UnCompress(_rawFile);

    }

    catch (ICSharpCode.SharpZipLib.SharpZipBaseException ex)

    {

    Logger.Current.Error(ex);

    throw;

    }

    }

    set

    {

    _rawFile = Compressor.Compress(value);

    }

    }

     

     

    I am storing the file in database through a stored procedure as follows

     

     

    oConn.Open();

    using (SqlCommand oCommand = new SqlCommand("proc_star_ins_upd_file", oConn))

    {

    oCommand.CommandType = System.Data.CommandType.StoredProcedure;

    oCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = ScrfFile.Id;

     

    oCommand.Parameters.Add("@file_name", SqlDbType.NVarChar, 50).Value = ScrfFile.FileName;

    oCommand.Parameters.Add("@contents", SqlDbType.Image, ScrfFile.RawFile.Length).Value = ScrfFile.RawFile;

    oCommand.Parameters.Add("@modify_by", SqlDbType.NVarChar, 150).Value = ScrfFile.ModifyBy;

    //oCommand.Parameters.Add("@modify_date", SqlDbType.DateTime, 150).Value = DateTime.Now;

    oCommand.ExecuteNonQuery();

    return true;

     

     

     

    PROBLEM

    I am getting back bytes[] of information when I retrieve the file.How do I reconstruct the original file back?

    Thursday, October 11, 2007 4:50 PM

Answers

  • Hi prashanth_prolific_coder,

     

    Write this byte array to FileStream.

     

    Code Block

    private void WriteToFile(string strFileName, byte[] info)

    {

    // Open the stream and write to it.

    using (System.IO.FileStream fs = System.IO.File.Create(strFileName))

    {

    // Add information to the file.

    fs.Write(info, 0, info.Length);

    }

    }

     

     

    Regards,
    Oleh.

    Friday, October 12, 2007 6:57 AM