zoukankan      html  css  js  c++  java
  • WPF 从服务器下载文件

    1、先获取服务器下载地址,给出要下载到的目标地址

    public void DownloadFileFromServer()
    {
       string serverFilePath = "http://192.168.1.222:9111/Doc/Test.docx";
       string serverFileName = string.Empty;
       int nameIndex = serverFilePath.LastIndexOf("/");
       if (nameIndex > 0)
       {
           serverFileName = serverFilePath.Substring(nameIndex + 1);
       }
       string dirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test");
       if (!Directory.Exists(dirPath))
       {
           DirectoryInfo directoryInfo = new DirectoryInfo(dirPath);
           directoryInfo.Create();
       }
       string targetPath = Path.Combine(dirPath, serverFileName);
       DownloadFile(serverFilePath, targetPath);
     }

    2、下载

    public void DownloadFile(string serverFilePath, string targetPath)
    {
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverFilePath);
       WebResponse respone = request.GetResponse();
       Stream netStream = respone.GetResponseStream();
       using (Stream fileStream = new FileStream(targetPath, FileMode.Create))
       {
          byte[] read = new byte[1024];
          int realReadLen = netStream.Read(read, 0, read.Length);
          while (realReadLen > 0)
          {
             fileStream.Write(read, 0, realReadLen);
             realReadLen = netStream.Read(read, 0, read.Length);
          }
          netStream.Close();
          fileStream.Close();
        }
     }
  • 相关阅读:
    程序员修炼之道阅读笔记02
    第十五周课堂练习-查找最长单词链
    文件读写总结
    第十五周
    暑假总结1
    软件工程课程总结
    第十六周总结
    用户场景分析
    学期课后个人总结
    第十五周总结
  • 原文地址:https://www.cnblogs.com/ElvisZhongShao/p/10846029.html
Copyright © 2011-2022 走看看