Question

I've some trouble to upload file from Memory Stream to database (it's visible in DB as 0x so i guess it doesn't get saved properly). I am not sure whether it's a problem with Stream being created or save to db from stream should be done differently.

private void test {
        byte[] storage = new byte[500000];
        using (MemoryStream stream = new MemoryStream(storage))
        DocX documentWord = DocX.Create(stream);
        // some stuff
        documentWord.Save(); 
        databaseFilePut(stream);
}


public static void databaseFilePut(MemoryStream stream) {
        byte[] file;
        using (var reader = new BinaryReader(stream)) {
                file = reader.ReadBytes((int) stream.Length);
               // reader.Close();
        }
            //stream.Close();
        //}
        using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
        using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(@File)", varConnection)) {
            sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
            sqlWrite.ExecuteNonQuery();
        }
    }

What am i doing wrong? I am using Docx codeplex library.

Was it helpful?

Solution

You're writing to the stream and then immediately trying to read from it without rewinding... so there's no data to read.

Fortunately, there's a very easy way of simplifying the code anyway:

byte[] file = stream.ToArray();

However, you've got another potential problem:

byte[] storage = new byte[500000];
using (MemoryStream stream = new MemoryStream(storage))
...

This will make the MemoryStream have a fixed size of 500K - no more, no less. I suspect that's not what you want; I suggest you get rid of the storage variable and just call the parameterless MemoryStream constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top