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(); } }