将上传的文件转成二进制流, 然后再解析成文件封存,为什么文件损坏了。

将上传的文件转成二进制流, 然后再解析成文件保存,为什么文件损坏了。。
做了个试验 通过二进制流的方法来传递中小型文件。。。


           //web上传文件,然后转成byte
            HttpFileCollection files = context.Request.Files;
            HttpPostedFile file = files[0];
            string fileName = file.FileName;
            //fileName = context.Server.MapPath("~/uploaded/" + fileName);
            //file.SaveAs(fileName);  //如果这里save的话,我查看过文件是完好的,可以打开
            Stream fs = file.InputStream;
            BinaryReader br = new BinaryReader(fs);
            byte[] bytes = br.ReadBytes((Int32)fs.Length);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();

           //将byte[]转回成文件
            FileStream fs2 = new FileStream("e:\\abc\\" + file.FileName, FileMode.Create, FileAccess.Write);
            fs2.Write(buffer, 0, buffer.Length);
            fs2.Flush();    
            fs2.Close();
           //转回形成的文件,文件大小没变,但不能用(图片渲染不来,音频文件播放器解析不出来)。。。。




我在网上查出来的方法都是,先保存在服务器,然后filestream读这个文件,转成二进制,再传输
我不想经过这步I/O,感觉这一步浪费资源啊。。。。 

我想直接将HttpPostedFile里的内容传递给别人,比如放一个web service接口专门获取文件二进制流,然后将二进制转成文件保存起来的。所以才有了上面的写法。

不知道要实现我的想法,各位大神有没什么高招。。。。
------解决方案--------------------
用windiff或者ultraedit比较下两个文件,看哪里的问题。
------解决方案--------------------
说明文件开头就没有写对。贴出UltraEdit显示的两个文件的开头一段。
------解决方案--------------------

using (Stream output = File.OpenWrite("c:\temp\file.zip"))
                    using (Stream input = file.InputStream)
                    {
                        byte[] buffer = new byte[8192];
                        int bytesRead;
                        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            output.Write(buffer, 0, bytesRead);
                        }
                    }


把上面的File.OpenWrite换成file.InputStream

http://*.com/questions/12927932/file-upload-with-c-sharp-and-streaming
------解决方案--------------------
引用:
HttpPostedFile类里的内容 没办法直接转成二进制存在byte[]中么。。。  难道必须要先保存下来,然后filestream读取这个文件才能转成二进制?


你去看看HttpWorkerRequest类吧,可以通过GetPreloadedEntityBody、ReadEntityBody方法在预加载阶段提前读取到客户端提交的数据,这里取出来的就是byte[],不过需要你自行从中分离出属于文件内容的部分
------解决方案--------------------
 HttpFileCollection files = context.Request.Files;
            HttpPostedFile file = files[0];
    
        int upPhotoLength = files.ContentLength;
        byte[] PhotoArray = new Byte[upPhotoLength];
        Stream PhotoStream = files.InputStream;
        PhotoStream.Read(PhotoArray, 0, upPhotoLength);