How to read and open files from a byte column in SQL Server?

0

My question is the continuation of this question: Link to another question

I was able to transform my file into bytes and insert it inside a table in SQL Server, however now I want from within an application that I'm doing in C # I want to open this file. That is to reverse engineer (byte > open the file).

The code used for insertion:

Anexo a = new Anexo();
FileStream fs = new FileStream(a.Caminho, FileMode.Open, FileAccess.Read);
a.Arquivo = new byte[fs.Length];
fs.Read(a.Arquivo, 0, System.Convert.ToInt32(fs.Length));
string SQL = @"INSERT INTO ANEXO (NOME, CAMINHO, ARQUIVO) VALUES (@nome, @caminho, @arquivo)";
Cmd = new SqlCommand(SQL, Con);
Cmd.Parameters.Add("@nome", SqlDbType.VarChar).Value = a.NomeArquivo;
Cmd.Parameters.Add("@caminho", SqlDbType.VarChar).Value = a.Caminho;
Cmd.Parameters.Add("@arquivo", SqlDbType.VarBinary).Value = a.Arquivo;
Cmd.ExecuteNonQuery();
    
asked by anonymous 09.12.2014 / 14:03

2 answers

2
  • Get the byte array and switch to a MemoryStream in the constructor;

  • Create your FileStream with the name of the file you want. I suppose you are saving at least the original file extension (the name is optional, but if you mix different files, it is worth saving a column with ".eml", ".txt", etc);

  • Read the bytes of MemoryStream and save in FileStream ;

  • If you open the file, you can call Process.Start .

  • // aqui está seu array de bytes
    byte[] arquivo;
    const int BufferSize = 65536;
    
    // create memory stream
    using (var mstrm = new MemoryStream(arquivo))
    {
        using (var outStream = File.Create("resultado.eml"))
        {
            var buffer = new byte[BufferSize];
            int bytesLidos;
            while ((bytesLidos = mstrm.Read(buffer, 0, BufferSize)) != 0)
            {
                outStream.Write(buffer, 0, bytesLidos);
            }
        }
    }
    

    Editing

    Use the following code to read the file in your byte array:

    public byte[] FileToByteArray(string fileName)
    {
        byte[] buff = null;
        FileStream fs = new FileStream(fileName, 
                                   FileMode.Open, 
                                   FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        long numBytes = new FileInfo(fileName).Length;
        buff = br.ReadBytes((int) numBytes);
        return buff;
    }
    

    It ensures that you can read large files! I know your files should not be too large, but if they have large attachments they can be a problem.

    To record, if it is not working, you can also use the way @Intruso pointed out too:

    File.WriteAllBytes(string caminho, byte[] array)
    
        
    10.12.2014 / 14:52
    1

    If your array represents a complete file:

    File.WriteAllBytes(string path, byte[] bytes)
    
        
    10.12.2014 / 14:51