C# 使用WebClient 取服务器文件转换为 Stream
根据服务文件地址保存到本地指定文件目录
#region 获取pdf文件 /// <summary> /// 获取pdf文件 /// </summary> /// <param name="serverUrl">服务器文件地址</param> /// <param name="localUrl">本地文件地址</param> public static void GetPdf(string serverUrl, string localUrl) { System.Net.WebClient myWebClient = new System.Net.WebClient(); myWebClient.DownloadFile(serverUrl, localUrl); } #endregion
根据本地文件路径将文件转换为Stream
#region 将文件转换为 Stream /// <summary> /// 将文件转换为 Stream /// </summary> /// <param name="fileName">文件路径</param> /// <returns></returns> public static Stream FileToStream(string fileName) { // 打开文件 FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); // 读取文件的 byte[] byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); // 把 byte[] 转换成 Stream Stream stream = new MemoryStream(bytes); return stream; } #endregion
根据服务文件地址将服务器文件转化为Stream
#region 将url文件转换为 Stream /// <summary> /// 将url文件转换为 Stream /// </summary> /// <param name="url">服务器文件地址</param> /// <returns></returns> public static Stream UrlToStream(string url) { WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(url); //下载到字节数组 Stream stream = new MemoryStream(bytes); return stream; } #endregion