开发者

Using MemoryStream to save .docx file C#

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 proble开发者_高级运维m 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜