.net 本地文件上传至服务器

来源:互联网 发布:网络奇谈恐惧鸟电子版 编辑:程序博客网 时间:2024/06/01 14:39

好久没写博客了,这里记录一个文件上传的方法:

本地文件上传至服务器

        /// <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;            }        }

也许这样的写法存在性能问题,这事参考官方写法写得。
官方链接:链接

原创粉丝点击