知识在于积累(.NET之路……)

导航

(C#) 将 Stream 写入文件

        /// <summary> 
        /// 将 Stream 写入文件 
        /// </summary> 
        public void StreamToFile(Stream stream, string fileName)
        {
            //isAlreadyRunning();
            //=========
            FileStream fs = null;
            BinaryWriter bw = null;
            try
            {
                // 把 Stream 转换成 byte[] 
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始 
                stream.Seek(0, SeekOrigin.Begin);

                // 把 byte[] 写入文件 
                if (!Directory.Exists(Server.MapPath("/SExcel/")))
                {
                    Directory.CreateDirectory(Server.MapPath("/SExcel/"));
                }
                fs = new FileStream(fileName, FileMode.Create);
                bw = new BinaryWriter(fs);
                bw.Write(bytes);
            }
            catch (Exception ex)
            {
                Alert.Show(ex.Message);
                return;
            }
            finally
            {
                bw.Close();
                fs.Close();
            }
        }

 

posted on 2012-05-29 10:31  汤尼  阅读(2472)  评论(0编辑  收藏  举报