FileHelper.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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 { throw; }
  212. }
  213. /// <summary>
  214. /// 创建一个文件,并将字节流写入文件。
  215. /// </summary>
  216. /// <param name="filePath">文件的绝对路径</param>
  217. /// <param name="buffer">二进制流数据</param>
  218. public static void CreateFile(string filePath, byte[] buffer)
  219. {
  220. try
  221. {
  222. //判断文件是否存在,不存在创建该文件
  223. if (!IsExistFile(filePath))
  224. {
  225. FileInfo file = new FileInfo(filePath);
  226. FileStream fs = file.Create();
  227. fs.Write(buffer, 0, buffer.Length);
  228. fs.Close();
  229. }
  230. else
  231. {
  232. File.WriteAllBytes(filePath, buffer);
  233. }
  234. }
  235. catch { throw; }
  236. }
  237. #endregion
  238. #region 将文件移动到指定目录
  239. /// <summary>
  240. /// 将文件移动到指定目录
  241. /// </summary>
  242. /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
  243. /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
  244. public static void Move(string sourceFilePath, string descDirectoryPath)
  245. {
  246. string sourceName = GetFileName(sourceFilePath);
  247. if (IsExistDirectory(descDirectoryPath))
  248. {
  249. //如果目标中存在同名文件,则删除
  250. if (IsExistFile(descDirectoryPath + "\\" + sourceFilePath))
  251. {
  252. DeleteFile(descDirectoryPath + "\\" + sourceFilePath);
  253. }
  254. else
  255. {
  256. //将文件移动到指定目录
  257. File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceName);
  258. }
  259. }
  260. }
  261. #endregion
  262. # region 将源文件的内容复制到目标文件中
  263. /// <summary>
  264. /// 将源文件的内容复制到目标文件中
  265. /// </summary>
  266. /// <param name="sourceFilePath">源文件的绝对路径</param>
  267. /// <param name="descDirectoryPath">目标文件的绝对路径</param>
  268. public static void Copy(string sourceFilePath, string descDirectoryPath)
  269. {
  270. File.Copy(sourceFilePath, descDirectoryPath, true);
  271. }
  272. #endregion
  273. #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
  274. /// <summary>
  275. /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
  276. /// </summary>
  277. /// <param name="filePath">文件的绝对路径</param>
  278. public static string GetFileName(string filePath)
  279. {
  280. FileInfo file = new FileInfo(filePath);
  281. return file.Name;
  282. }
  283. #endregion
  284. #region 获取文件的后缀名
  285. /// <summary>
  286. /// 获取文件的后缀名
  287. /// </summary>
  288. /// <param name="filePath">文件的绝对路径</param>
  289. public static string GetExtension(string filePath)
  290. {
  291. FileInfo file = new FileInfo(filePath);
  292. return file.Extension;
  293. }
  294. /// <summary>
  295. /// 返回文件扩展名,不含“.”
  296. /// </summary>
  297. /// <param name="filepath">文件全名称</param>
  298. /// <returns>string</returns>
  299. public static string GetFileExt(string filepath)
  300. {
  301. if (string.IsNullOrEmpty(filepath))
  302. {
  303. return "";
  304. }
  305. if (filepath.LastIndexOf(".", StringComparison.Ordinal) > 0)
  306. {
  307. return filepath.Substring(filepath.LastIndexOf(".", StringComparison.Ordinal) + 1); //文件扩展名,不含“.”
  308. }
  309. return "";
  310. }
  311. #endregion
  312. #region 删除指定文件
  313. /// <summary>
  314. /// 删除指定文件
  315. /// </summary>
  316. /// <param name="filePath">文件的绝对路径</param>
  317. public static void DeleteFile(string filePath)
  318. {
  319. if (IsExistFile(filePath))
  320. {
  321. File.Delete(filePath);
  322. }
  323. }
  324. #endregion
  325. // <summary>
  326. ///直接删除指定目录下的所有文件及文件夹(保留目录)
  327. /// </summary>
  328. /// <param name="strPath">文件夹路径</param>
  329. /// <returns>执行结果</returns>
  330. public static void DeleteDirAndFiles(string file)
  331. {
  332. try
  333. {
  334. //去除文件夹和子文件的只读属性
  335. //去除文件夹的只读属性
  336. System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
  337. fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
  338. //去除文件的只读属性
  339. System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
  340. //判断文件夹是否还存在
  341. if (Directory.Exists(file))
  342. {
  343. foreach (string f in Directory.GetFileSystemEntries(file))
  344. {
  345. if (File.Exists(f))
  346. {
  347. //如果有子文件删除文件
  348. File.Delete(f);
  349. }
  350. else
  351. {
  352. //循环递归删除子文件夹
  353. DeleteDirAndFiles(f);
  354. }
  355. }
  356. //删除空文件夹
  357. Directory.Delete(file);
  358. }
  359. }
  360. catch (Exception ex) // 异常处理
  361. {
  362. }
  363. }
  364. #region 删除指定目录及其所有子目录
  365. /// <summary>
  366. /// 删除指定目录及其所有子目录
  367. /// </summary>
  368. /// <param name="directoryPath">文件的绝对路径</param>
  369. public static void DeleteDirectory(string directoryPath)
  370. {
  371. if (IsExistDirectory(directoryPath))
  372. {
  373. Directory.Delete(directoryPath);
  374. }
  375. }
  376. #endregion
  377. #region 清空指定目录下所有文件及子目录,但该目录依然保存.
  378. /// <summary>
  379. /// 清空指定目录下所有文件及子目录,但该目录依然保存.
  380. /// </summary>
  381. /// <param name="directoryPath">指定目录的绝对路径</param>
  382. public static void ClearDirectory(string directoryPath)
  383. {
  384. if (!IsExistDirectory(directoryPath)) return;
  385. //删除目录中所有的文件
  386. string[] fileNames = GetFileNames(directoryPath);
  387. for (int i = 0; i < fileNames.Length; i++)
  388. {
  389. DeleteFile(fileNames[i]);
  390. }
  391. //删除目录中所有的子目录
  392. string[] directoryNames = GetDirectories(directoryPath);
  393. for (int i = 0; i < directoryNames.Length; i++)
  394. {
  395. DeleteDirectory(directoryNames[i]);
  396. }
  397. }
  398. #endregion
  399. #region 剪切 粘贴
  400. /// <summary>
  401. /// 剪切文件
  402. /// </summary>
  403. /// <param name="source">原路径</param>
  404. /// <param name="destination">新路径</param>
  405. public bool FileMove(string source, string destination)
  406. {
  407. bool ret = false;
  408. FileInfo file_s = new FileInfo(source);
  409. FileInfo file_d = new FileInfo(destination);
  410. if (file_s.Exists)
  411. {
  412. if (!file_d.Exists)
  413. {
  414. file_s.MoveTo(destination);
  415. ret = true;
  416. }
  417. }
  418. if (ret == true)
  419. {
  420. //Response.Write("<script>alert('剪切文件成功!');</script>");
  421. }
  422. else
  423. {
  424. //Response.Write("<script>alert('剪切文件失败!');</script>");
  425. }
  426. return ret;
  427. }
  428. #endregion
  429. #region 检测指定目录是否为空
  430. /// <summary>
  431. /// 检测指定目录是否为空
  432. /// </summary>
  433. /// <param name="directoryPath">指定目录的绝对路径</param>
  434. public static bool IsEmptyDirectory(string directoryPath)
  435. {
  436. try
  437. {
  438. //判断文件是否存在
  439. string[] fileNames = GetFileNames(directoryPath);
  440. if (fileNames.Length > 0)
  441. {
  442. return false;
  443. }
  444. //判断是否存在文件夹
  445. string[] directoryNames = GetDirectories(directoryPath);
  446. if (directoryNames.Length > 0)
  447. {
  448. return false;
  449. }
  450. return true;
  451. }
  452. catch (Exception ex)
  453. {
  454. var s = ex.Message;
  455. return true;
  456. }
  457. }
  458. #endregion
  459. #region 获取指定目录中所有文件列表
  460. /// <summary>
  461. /// 获取指定目录中所有文件列表
  462. /// </summary>
  463. /// <param name="directoryPath">指定目录的绝对路径</param>
  464. public static string[] GetFileNames(string directoryPath)
  465. {
  466. if (!IsExistDirectory(directoryPath))
  467. {
  468. throw new FileNotFoundException();
  469. }
  470. return Directory.GetFiles(directoryPath);
  471. }
  472. #endregion
  473. #region 获取指定目录中的子目录列表
  474. /// <summary>
  475. /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法
  476. /// </summary>
  477. /// <param name="directoryPath">指定目录的绝对路径</param>
  478. public static string[] GetDirectories(string directoryPath)
  479. {
  480. try
  481. {
  482. return Directory.GetDirectories(directoryPath);
  483. }
  484. catch { throw; }
  485. }
  486. /// <summary>
  487. /// 获取指定目录及子目录中所有子目录列表
  488. /// </summary>
  489. /// <param name="directoryPath">指定目录的绝对路径</param>
  490. /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
  491. /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
  492. /// <param name="isSearchChild">是否搜索子目录</param>
  493. public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
  494. {
  495. try
  496. {
  497. if (isSearchChild)
  498. {
  499. return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
  500. }
  501. else
  502. {
  503. return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
  504. }
  505. }
  506. catch { throw; }
  507. }
  508. #endregion
  509. #region 获取一个文件的长度
  510. /// <summary>
  511. /// 获取一个文件的长度,单位为Byte
  512. /// </summary>
  513. /// <param name="filePath">文件的绝对路径</param>
  514. public static int GetFileSize(string filePath)
  515. {
  516. //创建一个文件对象
  517. FileInfo fi = new FileInfo(filePath);
  518. //获取文件的大小
  519. return (int)fi.Length;
  520. }
  521. /// <summary>
  522. /// 获取一个文件的长度,单位为KB
  523. /// </summary>
  524. /// <param name="filePath">文件的路径</param>
  525. public static double GetFileSizeByKb(string filePath)
  526. {
  527. //创建一个文件对象
  528. FileInfo fi = new FileInfo(filePath);
  529. //获取文件的大小
  530. return Math.Round(Convert.ToDouble(filePath.Length) / 1024, 2);// ConvertHelper.ToDouble(ConvertHelper.ToDouble(fi.Length) / 1024, 1);
  531. }
  532. /// <summary>
  533. /// 获取一个文件的长度,单位为MB
  534. /// </summary>
  535. /// <param name="filePath">文件的路径</param>
  536. public static double GetFileSizeByMb(string filePath)
  537. {
  538. //创建一个文件对象
  539. FileInfo fi = new FileInfo(filePath);
  540. //获取文件的大小
  541. return Math.Round(Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024), 2);
  542. }
  543. #endregion
  544. #region 获取所有文件夹及子文件夹
  545. /// <summary>
  546. /// 获取所有文件夹及子文件夹
  547. /// </summary>
  548. /// <param name="dirPath"></param>
  549. /// <returns></returns>
  550. public static List<ArrayFiles> GetDirs(string dirPath)
  551. {
  552. var list = new List<ArrayFiles>();
  553. return GetArrys(dirPath, 0, list);
  554. }
  555. private static int zdId = 0;
  556. private static List<ArrayFiles> GetArrys(string dirPath, int pid, List<ArrayFiles> list)
  557. {
  558. if (!Directory.Exists(dirPath)) return list;
  559. if (Directory.GetDirectories(dirPath).Length <= 0) return list;
  560. foreach (string path in Directory.GetDirectories(dirPath))
  561. {
  562. zdId++;
  563. var model = new ArrayFiles()
  564. {
  565. Id = zdId,
  566. Name = path.Substring(path.LastIndexOf('\\') + 1, path.Length - (path.LastIndexOf('\\') + 1)),
  567. Pid = pid,
  568. Open = false,
  569. Target = "DeployBase",
  570. Url = "/FytAdmin/FileMiam/DocList?path=" + path
  571. };
  572. list.Add(model);
  573. GetArrys(path, model.Id, list);
  574. }
  575. return list;
  576. }
  577. public class ArrayFiles
  578. {
  579. public int Id { get; set; }
  580. public int Pid { get; set; }
  581. public string Name { get; set; }
  582. public Boolean Open { get; set; }
  583. public string Target { get; set; }
  584. public string Url { get; set; }
  585. }
  586. #endregion
  587. #region 将文件读取到字符串中
  588. /// <summary>
  589. /// 将文件读取到字符串中
  590. /// </summary>
  591. /// <param name="filePath">文件的绝对路径</param>
  592. public static string FileToString(string filePath)
  593. {
  594. return FileToString(filePath, Encoding.UTF8);
  595. }
  596. /// <summary>
  597. /// 将文件读取到字符串中
  598. /// </summary>
  599. /// <param name="filePath">文件的绝对路径</param>
  600. /// <param name="encoding">字符编码</param>
  601. public static string FileToString(string filePath, Encoding encoding)
  602. {
  603. //创建流读取器
  604. StreamReader reader = new StreamReader(filePath, encoding);
  605. try
  606. {
  607. //读取流
  608. return reader.ReadToEnd();
  609. }
  610. catch { throw; }
  611. finally
  612. {
  613. //关闭流读取器
  614. reader.Close();
  615. }
  616. }
  617. #endregion
  618. /// <summary>
  619. /// 列出文件夹下的所有子文件及子文件夹的子文件
  620. /// </summary>
  621. /// <param name="directoryPath"></param>
  622. /// <returns></returns>
  623. public static List<string> ListAllFiles(string directoryPath)
  624. {
  625. List<string> filePaths = new List<string>();
  626. DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
  627. // 获取目录下的所有文件(包括子目录中的文件)
  628. FileInfo[] files = dirInfo.GetFiles("*", SearchOption.AllDirectories);
  629. foreach (FileInfo file in files)
  630. {
  631. filePaths.Add(file.FullName);
  632. // Console.WriteLine(file.FullName);
  633. }
  634. return filePaths;
  635. }
  636. }
  637. /// <summary>
  638. /// 远程文件下载
  639. /// </summary>
  640. public class HttpDldFile
  641. {
  642. /// <summary>
  643. /// Http方式下载文件
  644. /// </summary>
  645. /// <param name="url">http地址</param>
  646. /// <param name="localfile">本地文件</param>
  647. /// <returns></returns>
  648. public bool Download(string url, string localfile)
  649. {
  650. bool flag = false;
  651. long startPosition = 0; // 上次下载的文件起始位置
  652. FileStream writeStream; // 写入本地文件流对象
  653. long remoteFileLength = GetHttpLength(url);// 取得远程文件长度
  654. //System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
  655. if (remoteFileLength == 745)
  656. {
  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. writeStream.Close();
  667. return false;
  668. }
  669. else
  670. {
  671. writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
  672. }
  673. }
  674. else
  675. {
  676. writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
  677. startPosition = 0;
  678. }
  679. try
  680. {
  681. HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
  682. if (startPosition > 0)
  683. {
  684. myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
  685. }
  686. Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
  687. byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
  688. int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次
  689. long currPostion = startPosition;
  690. while (contentSize > 0)// 如果读取长度大于零则继续读
  691. {
  692. currPostion += contentSize;
  693. int percent = (int)(currPostion * 100 / remoteFileLength);
  694. writeStream.Write(btArray, 0, contentSize);// 写入本地文件
  695. contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
  696. }
  697. //关闭流
  698. writeStream.Close();
  699. readStream.Close();
  700. flag = true; //返回true下载成功
  701. }
  702. catch (Exception)
  703. {
  704. writeStream.Close();
  705. flag = false; //返回false下载失败
  706. }
  707. return flag;
  708. }
  709. // 从文件头得到远程文件的长度
  710. private static long GetHttpLength(string url)
  711. {
  712. long length = 0;
  713. try
  714. {
  715. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
  716. HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
  717. if (rsp.StatusCode == HttpStatusCode.OK)
  718. {
  719. length = rsp.ContentLength;// 从文件头得到远程文件的长度
  720. }
  721. rsp.Close();
  722. return length;
  723. }
  724. catch (Exception e)
  725. {
  726. var s = e.Message;
  727. return length;
  728. }
  729. }
  730. }
  731. }