FileHelper.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. namespace TEAMModelOS.SDK.Helper.Common.FileHelper
  8. {
  9. public class FileHelper
  10. {
  11. #region 获取文件到集合中
  12. /// <summary>
  13. /// 读取指定位置文件列表到集合中
  14. /// </summary>
  15. /// <param name="path">指定路径</param>
  16. /// <returns></returns>
  17. public static DataTable GetFileTable(string path)
  18. {
  19. DataTable dt = new DataTable();
  20. dt.Columns.Add("name", typeof(string));
  21. dt.Columns.Add("ext", typeof(string));
  22. dt.Columns.Add("size", typeof(long));
  23. dt.Columns.Add("time", typeof(DateTime));
  24. DirectoryInfo dirinfo = new DirectoryInfo(path);
  25. FileInfo fi;
  26. DirectoryInfo dir;
  27. string FileName, FileExt;
  28. long FileSize = 0;
  29. DateTime FileModify;
  30. try
  31. {
  32. foreach (FileSystemInfo fsi in dirinfo.GetFileSystemInfos())
  33. {
  34. FileName = string.Empty;
  35. FileExt = string.Empty;
  36. if (fsi is FileInfo)
  37. {
  38. fi = (FileInfo)fsi;
  39. //获取文件名称
  40. FileName = fi.Name;
  41. //获取文件扩展名
  42. FileExt = fi.Extension;
  43. //获取文件大小
  44. FileSize = fi.Length;
  45. //获取文件最后修改时间
  46. FileModify = fi.LastWriteTime;
  47. }
  48. else
  49. {
  50. dir = (DirectoryInfo)fsi;
  51. //获取目录名
  52. FileName = dir.Name;
  53. //获取目录最后修改时间
  54. FileModify = dir.LastWriteTime;
  55. //设置目录文件为文件夹
  56. FileExt = "文件夹";
  57. }
  58. DataRow dr = dt.NewRow();
  59. dr["name"] = FileName;
  60. dr["ext"] = FileExt;
  61. dr["size"] = FileSize;
  62. dr["time"] = FileModify;
  63. dt.Rows.Add(dr);
  64. }
  65. }
  66. catch
  67. {
  68. throw;
  69. }
  70. return dt;
  71. }
  72. #endregion
  73. #region 检测指定路径是否存在
  74. /// <summary>
  75. /// 检测指定路径是否存在
  76. /// </summary>
  77. /// <param name="path">目录的绝对路径</param>
  78. public static bool IsExistDirectory(string path)
  79. {
  80. return Directory.Exists(path);
  81. }
  82. #endregion
  83. #region 检测指定文件是否存在,如果存在则返回true
  84. /// <summary>
  85. /// 检测指定文件是否存在,如果存在则返回true
  86. /// </summary>
  87. /// <param name="filePath">文件的绝对路径</param>
  88. public static bool IsExistFile(string filePath)
  89. {
  90. return File.Exists(filePath);
  91. }
  92. #endregion
  93. #region 创建文件夹
  94. /// <summary>
  95. /// 创建文件夹
  96. /// </summary>
  97. /// <param name="folderPath">文件夹的绝对路径</param>
  98. public static void CreateFolder(string folderPath)
  99. {
  100. if (!IsExistDirectory(folderPath))
  101. {
  102. Directory.CreateDirectory(folderPath);
  103. }
  104. }
  105. #endregion
  106. #region 判断上传文件后缀名
  107. /// <summary>
  108. /// 判断上传文件后缀名
  109. /// </summary>
  110. /// <param name="strExtension">后缀名</param>
  111. public static bool IsCanEdit(string strExtension)
  112. {
  113. strExtension = strExtension.ToLower();
  114. if (strExtension.LastIndexOf(".", StringComparison.Ordinal) >= 0)
  115. {
  116. strExtension = strExtension.Substring(strExtension.LastIndexOf(".", StringComparison.Ordinal));
  117. }
  118. else
  119. {
  120. strExtension = ".txt";
  121. }
  122. string[] strArray = new string[] { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
  123. for (int i = 0; i < strArray.Length; i++)
  124. {
  125. if (strExtension.Equals(strArray[i]))
  126. {
  127. return true;
  128. }
  129. }
  130. return false;
  131. }
  132. public static bool IsSafeName(string strExtension)
  133. {
  134. strExtension = strExtension.ToLower();
  135. if (strExtension.LastIndexOf(".") >= 0)
  136. {
  137. strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
  138. }
  139. else
  140. {
  141. strExtension = ".txt";
  142. }
  143. string[] strArray = new string[] { ".jpg", ".gif", ".png" };
  144. for (int i = 0; i < strArray.Length; i++)
  145. {
  146. if (strExtension.Equals(strArray[i]))
  147. {
  148. return true;
  149. }
  150. }
  151. return false;
  152. }
  153. public static bool IsZipName(string strExtension)
  154. {
  155. strExtension = strExtension.ToLower();
  156. if (strExtension.LastIndexOf(".") >= 0)
  157. {
  158. strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
  159. }
  160. else
  161. {
  162. strExtension = ".txt";
  163. }
  164. string[] strArray = new string[] { ".zip", ".rar" };
  165. for (int i = 0; i < strArray.Length; i++)
  166. {
  167. if (strExtension.Equals(strArray[i]))
  168. {
  169. return true;
  170. }
  171. }
  172. return false;
  173. }
  174. #endregion
  175. #region 创建文件夹
  176. /// <summary>
  177. /// 创建文件夹
  178. /// </summary>
  179. /// <param name="fileName">文件的绝对路径</param>
  180. public static void CreateSuffic(string fileName)
  181. {
  182. try
  183. {
  184. if (!Directory.Exists(fileName))
  185. {
  186. Directory.CreateDirectory(fileName);
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. var s = ex.Message;
  192. throw;
  193. }
  194. }
  195. /// <summary>
  196. /// 创建文件夹
  197. /// </summary>
  198. /// <param name="fileName">文件的绝对路径</param>
  199. public static void CreateFiles(string fileName)
  200. {
  201. try
  202. {
  203. //判断文件是否存在,不存在创建该文件
  204. if (!IsExistFile(fileName))
  205. {
  206. FileInfo file = new FileInfo(fileName);
  207. FileStream fs = file.Create();
  208. fs.Close();
  209. }
  210. }
  211. catch (Exception ex)
  212. {
  213. throw ex;
  214. }
  215. }
  216. /// <summary>
  217. /// 创建一个文件,并将字节流写入文件。
  218. /// </summary>
  219. /// <param name="filePath">文件的绝对路径</param>
  220. /// <param name="buffer">二进制流数据</param>
  221. public static void CreateFile(string filePath, byte[] buffer)
  222. {
  223. try
  224. {
  225. //判断文件是否存在,不存在创建该文件
  226. if (!IsExistFile(filePath))
  227. {
  228. FileInfo file = new FileInfo(filePath);
  229. FileStream fs = file.Create();
  230. fs.Write(buffer, 0, buffer.Length);
  231. fs.Close();
  232. }
  233. else
  234. {
  235. File.WriteAllBytes(filePath, buffer);
  236. }
  237. }
  238. catch (Exception ex)
  239. {
  240. throw ex;
  241. }
  242. }
  243. #endregion
  244. #region 将文件移动到指定目录
  245. /// <summary>
  246. /// 将文件移动到指定目录
  247. /// </summary>
  248. /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
  249. /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
  250. public static void Move(string sourceFilePath, string descDirectoryPath)
  251. {
  252. string sourceName = GetFileName(sourceFilePath);
  253. if (IsExistDirectory(descDirectoryPath))
  254. {
  255. //如果目标中存在同名文件,则删除
  256. if (IsExistFile(descDirectoryPath + "\\" + sourceFilePath))
  257. {
  258. DeleteFile(descDirectoryPath + "\\" + sourceFilePath);
  259. }
  260. else
  261. {
  262. //将文件移动到指定目录
  263. File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFilePath);
  264. }
  265. }
  266. }
  267. #endregion
  268. # region 将源文件的内容复制到目标文件中
  269. /// <summary>
  270. /// 将源文件的内容复制到目标文件中
  271. /// </summary>
  272. /// <param name="sourceFilePath">源文件的绝对路径</param>
  273. /// <param name="descDirectoryPath">目标文件的绝对路径</param>
  274. public static void Copy(string sourceFilePath, string descDirectoryPath)
  275. {
  276. File.Copy(sourceFilePath, descDirectoryPath, true);
  277. }
  278. #endregion
  279. #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
  280. /// <summary>
  281. /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
  282. /// </summary>
  283. /// <param name="filePath">文件的绝对路径</param>
  284. public static string GetFileName(string filePath)
  285. {
  286. FileInfo file = new FileInfo(filePath);
  287. return file.Name;
  288. }
  289. #endregion
  290. #region 获取文件的后缀名
  291. /// <summary>
  292. /// 获取文件的后缀名
  293. /// </summary>
  294. /// <param name="filePath">文件的绝对路径</param>
  295. public static string GetExtension(string filePath)
  296. {
  297. FileInfo file = new FileInfo(filePath);
  298. return file.Extension;
  299. }
  300. /// <summary>
  301. /// 返回文件扩展名,不含“.”
  302. /// </summary>
  303. /// <param name="filepath">文件全名称</param>
  304. /// <returns>string</returns>
  305. public static string GetFileExt(string filepath)
  306. {
  307. if (string.IsNullOrEmpty(filepath))
  308. {
  309. return "";
  310. }
  311. if (filepath.LastIndexOf(".", StringComparison.Ordinal) > 0)
  312. {
  313. return filepath.Substring(filepath.LastIndexOf(".", StringComparison.Ordinal) + 1); //文件扩展名,不含“.”
  314. }
  315. return "";
  316. }
  317. #endregion
  318. #region 删除指定文件
  319. /// <summary>
  320. /// 删除指定文件
  321. /// </summary>
  322. /// <param name="filePath">文件的绝对路径</param>
  323. public static void DeleteFile(string filePath)
  324. {
  325. if (IsExistFile(filePath))
  326. {
  327. File.Delete(filePath);
  328. }
  329. }
  330. #endregion
  331. // <summary>
  332. ///直接删除指定目录下的所有文件及文件夹(保留目录)
  333. /// </summary>
  334. /// <param name="strPath">文件夹路径</param>
  335. /// <returns>执行结果</returns>
  336. public static void DeleteDirAndFiles(string file)
  337. {
  338. try
  339. {
  340. //去除文件夹和子文件的只读属性
  341. //去除文件夹的只读属性
  342. System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
  343. fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
  344. //去除文件的只读属性
  345. System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
  346. //判断文件夹是否还存在
  347. if (Directory.Exists(file))
  348. {
  349. foreach (string f in Directory.GetFileSystemEntries(file))
  350. {
  351. if (File.Exists(f))
  352. {
  353. //如果有子文件删除文件
  354. File.Delete(f);
  355. Console.WriteLine(f);
  356. }
  357. else
  358. {
  359. //循环递归删除子文件夹
  360. DeleteDirAndFiles(f);
  361. }
  362. }
  363. //删除空文件夹
  364. Directory.Delete(file);
  365. }
  366. }
  367. catch (Exception ex) // 异常处理
  368. {
  369. Console.WriteLine(ex.Message.ToString());// 异常信息
  370. }
  371. }
  372. #region 删除指定目录及其所有子目录
  373. /// <summary>
  374. /// 删除指定目录及其所有子目录
  375. /// </summary>
  376. /// <param name="directoryPath">文件的绝对路径</param>
  377. public static void DeleteDirectory(string directoryPath)
  378. {
  379. if (IsExistDirectory(directoryPath))
  380. {
  381. Directory.Delete(directoryPath);
  382. }
  383. }
  384. #endregion
  385. #region 清空指定目录下所有文件及子目录,但该目录依然保存.
  386. /// <summary>
  387. /// 清空指定目录下所有文件及子目录,但该目录依然保存.
  388. /// </summary>
  389. /// <param name="directoryPath">指定目录的绝对路径</param>
  390. public static void ClearDirectory(string directoryPath)
  391. {
  392. if (!IsExistDirectory(directoryPath)) return;
  393. //删除目录中所有的文件
  394. string[] fileNames = GetFileNames(directoryPath);
  395. for (int i = 0; i < fileNames.Length; i++)
  396. {
  397. DeleteFile(fileNames[i]);
  398. }
  399. //删除目录中所有的子目录
  400. string[] directoryNames = GetDirectories(directoryPath);
  401. for (int i = 0; i < directoryNames.Length; i++)
  402. {
  403. DeleteDirectory(directoryNames[i]);
  404. }
  405. }
  406. #endregion
  407. #region 剪切 粘贴
  408. /// <summary>
  409. /// 剪切文件
  410. /// </summary>
  411. /// <param name="source">原路径</param>
  412. /// <param name="destination">新路径</param>
  413. public bool FileMove(string source, string destination)
  414. {
  415. bool ret = false;
  416. FileInfo file_s = new FileInfo(source);
  417. FileInfo file_d = new FileInfo(destination);
  418. if (file_s.Exists)
  419. {
  420. if (!file_d.Exists)
  421. {
  422. file_s.MoveTo(destination);
  423. ret = true;
  424. }
  425. }
  426. if (ret == true)
  427. {
  428. //Response.Write("<script>alert('剪切文件成功!');</script>");
  429. }
  430. else
  431. {
  432. //Response.Write("<script>alert('剪切文件失败!');</script>");
  433. }
  434. return ret;
  435. }
  436. #endregion
  437. #region 检测指定目录是否为空
  438. /// <summary>
  439. /// 检测指定目录是否为空
  440. /// </summary>
  441. /// <param name="directoryPath">指定目录的绝对路径</param>
  442. public static bool IsEmptyDirectory(string directoryPath)
  443. {
  444. try
  445. {
  446. //判断文件是否存在
  447. string[] fileNames = GetFileNames(directoryPath);
  448. if (fileNames.Length > 0)
  449. {
  450. return false;
  451. }
  452. //判断是否存在文件夹
  453. string[] directoryNames = GetDirectories(directoryPath);
  454. if (directoryNames.Length > 0)
  455. {
  456. return false;
  457. }
  458. return true;
  459. }
  460. catch (Exception ex)
  461. {
  462. var s = ex.Message;
  463. return true;
  464. }
  465. }
  466. #endregion
  467. #region 获取指定目录中所有文件列表
  468. /// <summary>
  469. /// 获取指定目录中所有文件列表
  470. /// </summary>
  471. /// <param name="directoryPath">指定目录的绝对路径</param>
  472. public static string[] GetFileNames(string directoryPath)
  473. {
  474. if (!IsExistDirectory(directoryPath))
  475. {
  476. throw new FileNotFoundException();
  477. }
  478. return Directory.GetFiles(directoryPath);
  479. }
  480. #endregion
  481. #region 获取指定目录中的子目录列表
  482. /// <summary>
  483. /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法
  484. /// </summary>
  485. /// <param name="directoryPath">指定目录的绝对路径</param>
  486. public static string[] GetDirectories(string directoryPath)
  487. {
  488. try
  489. {
  490. return Directory.GetDirectories(directoryPath);
  491. }
  492. catch (Exception ex)
  493. {
  494. throw ex;
  495. }
  496. }
  497. /// <summary>
  498. /// 获取指定目录及子目录中所有子目录列表
  499. /// </summary>
  500. /// <param name="directoryPath">指定目录的绝对路径</param>
  501. /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
  502. /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
  503. /// <param name="isSearchChild">是否搜索子目录</param>
  504. public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
  505. {
  506. try
  507. {
  508. if (isSearchChild)
  509. {
  510. return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
  511. }
  512. else
  513. {
  514. return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
  515. }
  516. }
  517. catch (Exception ex)
  518. {
  519. throw ex;
  520. }
  521. }
  522. #endregion
  523. #region 获取一个文件的长度
  524. /// <summary>
  525. /// 获取一个文件的长度,单位为Byte
  526. /// </summary>
  527. /// <param name="filePath">文件的绝对路径</param>
  528. public static int GetFileSize(string filePath)
  529. {
  530. //创建一个文件对象
  531. FileInfo fi = new FileInfo(filePath);
  532. //获取文件的大小
  533. return (int)fi.Length;
  534. }
  535. /// <summary>
  536. /// 获取一个文件的长度,单位为KB
  537. /// </summary>
  538. /// <param name="filePath">文件的路径</param>
  539. public static double GetFileSizeByKb(string filePath)
  540. {
  541. //创建一个文件对象
  542. FileInfo fi = new FileInfo(filePath);
  543. //获取文件的大小
  544. return Math.Round(Convert.ToDouble(filePath.Length) / 1024, 2);// ConvertHelper.ToDouble(ConvertHelper.ToDouble(fi.Length) / 1024, 1);
  545. }
  546. /// <summary>
  547. /// 获取一个文件的长度,单位为MB
  548. /// </summary>
  549. /// <param name="filePath">文件的路径</param>
  550. public static double GetFileSizeByMb(string filePath)
  551. {
  552. //创建一个文件对象
  553. FileInfo fi = new FileInfo(filePath);
  554. //获取文件的大小
  555. return Math.Round(Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024), 2);
  556. }
  557. #endregion
  558. #region 获取所有文件夹及子文件夹
  559. /// <summary>
  560. /// 获取所有文件夹及子文件夹
  561. /// </summary>
  562. /// <param name="dirPath"></param>
  563. /// <returns></returns>
  564. public static List<ArrayFiles> GetDirs(string dirPath)
  565. {
  566. var list = new List<ArrayFiles>();
  567. return GetArrys(dirPath, 0, list);
  568. }
  569. private static int zdId = 0;
  570. private static List<ArrayFiles> GetArrys(string dirPath, int pid, List<ArrayFiles> list)
  571. {
  572. if (!Directory.Exists(dirPath)) return list;
  573. if (Directory.GetDirectories(dirPath).Length <= 0) return list;
  574. foreach (string path in Directory.GetDirectories(dirPath))
  575. {
  576. zdId++;
  577. var model = new ArrayFiles()
  578. {
  579. Id = zdId,
  580. Name = path.Substring(path.LastIndexOf('\\') + 1, path.Length - (path.LastIndexOf('\\') + 1)),
  581. Pid = pid,
  582. Open = false,
  583. Target = "DeployBase",
  584. Url = "/FytAdmin/FileMiam/DocList?path=" + path
  585. };
  586. list.Add(model);
  587. GetArrys(path, model.Id, list);
  588. }
  589. return list;
  590. }
  591. public class ArrayFiles
  592. {
  593. public int Id { get; set; }
  594. public int Pid { get; set; }
  595. public string Name { get; set; }
  596. public Boolean Open { get; set; }
  597. public string Target { get; set; }
  598. public string Url { get; set; }
  599. }
  600. #endregion
  601. #region 将文件读取到字符串中
  602. /// <summary>
  603. /// 将文件读取到字符串中
  604. /// </summary>
  605. /// <param name="filePath">文件的绝对路径</param>
  606. public static string FileToString(string filePath)
  607. {
  608. return FileToString(filePath, Encoding.UTF8);
  609. }
  610. /// <summary>
  611. /// 将文件读取到字符串中
  612. /// </summary>
  613. /// <param name="filePath">文件的绝对路径</param>
  614. /// <param name="encoding">字符编码</param>
  615. public static string FileToString(string filePath, Encoding encoding)
  616. {
  617. //创建流读取器
  618. StreamReader reader = new StreamReader(filePath, encoding);
  619. try
  620. {
  621. //读取流
  622. return reader.ReadToEnd();
  623. }
  624. catch (Exception ex)
  625. {
  626. throw ex;
  627. }
  628. finally
  629. {
  630. //关闭流读取器
  631. reader.Close();
  632. }
  633. }
  634. #endregion
  635. }
  636. /// <summary>
  637. /// 远程文件下载
  638. /// </summary>
  639. public class HttpDldFile
  640. {
  641. /// <summary>
  642. /// Http方式下载文件
  643. /// </summary>
  644. /// <param name="url">http地址</param>
  645. /// <param name="localfile">本地文件</param>
  646. /// <returns></returns>
  647. public bool Download(string url, string localfile)
  648. {
  649. bool flag = false;
  650. long startPosition = 0; // 上次下载的文件起始位置
  651. FileStream writeStream; // 写入本地文件流对象
  652. long remoteFileLength = GetHttpLength(url);// 取得远程文件长度
  653. //System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
  654. if (remoteFileLength == 745)
  655. {
  656. System.Console.WriteLine("远程文件不存在.");
  657. return false;
  658. }
  659. // 判断要下载的文件夹是否存在
  660. if (File.Exists(localfile))
  661. {
  662. writeStream = File.OpenWrite(localfile); // 存在则打开要下载的文件
  663. startPosition = writeStream.Length; // 获取已经下载的长度
  664. if (startPosition >= remoteFileLength)
  665. {
  666. System.Console.WriteLine("本地文件长度" + startPosition + "已经大于等于远程文件长度" + remoteFileLength);
  667. writeStream.Close();
  668. return false;
  669. }
  670. else
  671. {
  672. writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
  673. }
  674. }
  675. else
  676. {
  677. writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
  678. startPosition = 0;
  679. }
  680. try
  681. {
  682. HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
  683. if (startPosition > 0)
  684. {
  685. myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
  686. }
  687. Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
  688. byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
  689. int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次
  690. long currPostion = startPosition;
  691. while (contentSize > 0)// 如果读取长度大于零则继续读
  692. {
  693. currPostion += contentSize;
  694. int percent = (int)(currPostion * 100 / remoteFileLength);
  695. System.Console.WriteLine("percent=" + percent + "%");
  696. writeStream.Write(btArray, 0, contentSize);// 写入本地文件
  697. contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
  698. }
  699. //关闭流
  700. writeStream.Close();
  701. readStream.Close();
  702. flag = true; //返回true下载成功
  703. }
  704. catch (Exception)
  705. {
  706. writeStream.Close();
  707. flag = false; //返回false下载失败
  708. }
  709. return flag;
  710. }
  711. // 从文件头得到远程文件的长度
  712. private static long GetHttpLength(string url)
  713. {
  714. long length = 0;
  715. try
  716. {
  717. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
  718. HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
  719. if (rsp.StatusCode == HttpStatusCode.OK)
  720. {
  721. length = rsp.ContentLength;// 从文件头得到远程文件的长度
  722. }
  723. rsp.Close();
  724. return length;
  725. }
  726. catch (Exception e)
  727. {
  728. var s = e.Message;
  729. return length;
  730. }
  731. }
  732. }
  733. }