您的位置:首页 > 其它

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

2017-06-26 19:48 295 查看
好久没写博客了,这里记录一个文件上传的方法:

本地文件上传至服务器

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


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

官方链接:链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息