c# - File is saved through Stream but can't be opened -


i'm trying save image in d: directory, , accomplish this, i'm save in session informations fileupload component.

in method called btnconfirm_click create session , in btnsave_click method recover information , try save file, when check in d: directory, file exist when open file, saw message: the windows photo viewer can not open picture because file appears damaged, corrupted, or big ..

someone can me ?

c# code

protected void btnconfirm_click(object sender, eventargs e) {  if (fileupload1.hasfile)             {                 string sfilename = fileupload1.filename;                 string fileextension = system.io.path.getextension(sfilename).tolower();                 foreach (string ext in new string[] { ".jpeg", ".jpg", ".png" })                 {                     if (fileextension == ext)                     {                         session["document"] = sfilename + fileextension;                         session["byte"] = fileupload1.filebytes;                         session["content"] = fileupload1.filecontent;                         byte[] b = (byte[])session["byte"];                     }                 }            } }   protected void btnsave_click(object sender, eventargs e)         {                 if (session["document"].tostring() != null)                 {                     try                     {                         byte[] bytearray = encoding.utf8.getbytes(session["content"].tostring());                                                 memorystream stream = new memorystream(bytearray);                          spath = "d:/123.jpg";                         filestream filestream = file.create(spath, (int)stream.length);                                                 byte[] bytesinstream = new byte[stream.length];                         stream.read(bytesinstream, 0, bytesinstream.length);                                                 filestream.write(bytesinstream, 0, bytesinstream.length);                     }                     catch                     {                     }               }          } 

byte[] bytearray = encoding.utf8.getbytes(session["content"].tostring()); 

this line looks wrong. taking string (encoded utf8) , trying turn binary jpg image. won't work. need keep original image in binary (not textual + encoding) form. when turn byte[] string (or vice-versa) there information loss because textual encoding can't (in general) represent byte sequence.

as @panagiotiskanovas mentions, want getting session['content'] stream of data.

as aside, aren't closing streams, it's possible when try open file object still locked.

using (filestream filestream = file.create(spath, (int)stream.length)) {    byte[] bytesinstream = new byte[stream.length];    stream.read(bytesinstream, 0, bytesinstream.length);                            filestream.write(bytesinstream, 0, bytesinstream.length); } 

Comments