Using MemoryStream to save a .docx C # file

I have some problems downloading a file from Memory Stream to the database (it appears in DB as 0x, so I think it is not saved properly). I am not sure that the problem of creating a stream or storing in db from a 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 the Docx codeplex library.

+6
memorystream docx
source share
1 answer

You write a stream, and then immediately try to read it without rewinding ... so there is no data to read.

Fortunately, there is a very simple way to simplify the code:

 byte[] file = stream.ToArray(); 

However, you have another potential problem:

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

This will lead to the fact that the MemoryStream will have a fixed size of 500K - no more, no less. I suspect that is not what you want; I suggest you get rid of the storage variable and just call the constructor without MemoryStream parameters.

+7
source share

All Articles