.net 文件上传到服务器【转】

最忌你在一个文档管理系统,包裹文件上传下载等。

http://blog.csdn.net/pmy_c_l/article/details/73743843

官方链接:https://msdn.microsoft.com/zh-cn/library/system.io.filestream.read.aspx

        /// <summary>
        /// 读取本地文件上传到服务器
        /// </summary>
        /// <param name="localfilepath">本地文件路径</param>
        /// <param name="serverpath">服务器存储路径</param>
        public void ReadFile(string localfilepath, string serverpath)
        {
            //string filepath = "C:\xxx";//文件上传本地地址;
            //string serverpath = HttpContext.Current.Server.MapPath("../File/" + fileName); //保存在服务器上的路径            
            try
            {
                FileInfo fs = new FileInfo(localfilepath);
                string fileName = fs.Name;  //获取文件名
                using (FileStream fsRead = new FileStream(localfilepath, FileMode.Open))
                {
                    using (FileStream fsWrite = new FileStream(serverpath, FileMode.OpenOrCreate))
                    {//自定义数组的长度
                        byte[] bytes = new byte[fsRead.Length];
                        //当没有读取到文件的末尾的时候就需要循环读取
                        while (fsRead.Position < fsRead.Length)
                        {//读取的时候position属性会自动变化,记住当前读取到的位置,以字节为单位
                            //count可以获取当前具体读取到的字节数
                            int count = fsRead.Read(bytes, 0, bytes.Length);
                            if (count == 0) { break; }                            
                        }
                        //写入
                        fsWrite.Write(bytes, 0, fsRead.Length); //只需要写入读取到的字节数就可以了
                    }
                } 
            }
            catch (Exception e)
            {
                throw e;
            }
        }

 

posted @ 2017-09-13 17:48  哈库拉灬玛塔塔  阅读(373)  评论(0编辑  收藏  举报