FileHelper.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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 + "\\" + sourceFilePath);
  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. Console.WriteLine(f);
  350. }
  351. else
  352. {
  353. //循环递归删除子文件夹
  354. DeleteDirAndFiles(f);
  355. }
  356. }
  357. //删除空文件夹
  358. Directory.Delete(file);
  359. }
  360. }
  361. catch (Exception ex) // 异常处理
  362. {
  363. Console.WriteLine(ex.Message.ToString());// 异常信息
  364. }
  365. }
  366. #region 删除指定目录及其所有子目录
  367. /// <summary>
  368. /// 删除指定目录及其所有子目录
  369. /// </summary>
  370. /// <param name="directoryPath">文件的绝对路径</param>
  371. public static void DeleteDirectory(string directoryPath)
  372. {
  373. if (IsExistDirectory(directoryPath))
  374. {
  375. Directory.Delete(directoryPath);
  376. }
  377. }
  378. #endregion
  379. #region 清空指定目录下所有文件及子目录,但该目录依然保存.
  380. /// <summary>
  381. /// 清空指定目录下所有文件及子目录,但该目录依然保存.
  382. /// </summary>
  383. /// <param name="directoryPath">指定目录的绝对路径</param>
  384. public static void ClearDirectory(string directoryPath)
  385. {
  386. if (!IsExistDirectory(directoryPath)) return;
  387. //删除目录中所有的文件
  388. string[] fileNames = GetFileNames(directoryPath);
  389. for (int i = 0; i < fileNames.Length; i++)
  390. {
  391. DeleteFile(fileNames[i]);
  392. }
  393. //删除目录中所有的子目录
  394. string[] directoryNames = GetDirectories(directoryPath);
  395. for (int i = 0; i < directoryNames.Length; i++)
  396. {
  397. DeleteDirectory(directoryNames[i]);
  398. }
  399. }
  400. #endregion
  401. #region 剪切 粘贴
  402. /// <summary>
  403. /// 剪切文件
  404. /// </summary>
  405. /// <param name="source">原路径</param>
  406. /// <param name="destination">新路径</param>
  407. public bool FileMove(string source, string destination)
  408. {
  409. bool ret = false;
  410. FileInfo file_s = new FileInfo(source);
  411. FileInfo file_d = new FileInfo(destination);
  412. if (file_s.Exists)
  413. {
  414. if (!file_d.Exists)
  415. {
  416. file_s.MoveTo(destination);
  417. ret = true;
  418. }
  419. }
  420. if (ret == true)
  421. {
  422. //Response.Write("<script>alert('剪切文件成功!');</script>");
  423. }
  424. else
  425. {
  426. //Response.Write("<script>alert('剪切文件失败!');</script>");
  427. }
  428. return ret;
  429. }
  430. #endregion
  431. #region 检测指定目录是否为空
  432. /// <summary>
  433. /// 检测指定目录是否为空
  434. /// </summary>
  435. /// <param name="directoryPath">指定目录的绝对路径</param>
  436. public static bool IsEmptyDirectory(string directoryPath)
  437. {
  438. try
  439. {
  440. //判断文件是否存在
  441. string[] fileNames = GetFileNames(directoryPath);
  442. if (fileNames.Length > 0)
  443. {
  444. return false;
  445. }
  446. //判断是否存在文件夹
  447. string[] directoryNames = GetDirectories(directoryPath);
  448. if (directoryNames.Length > 0)
  449. {
  450. return false;
  451. }
  452. return true;
  453. }
  454. catch (Exception ex)
  455. {
  456. var s = ex.Message;
  457. return true;
  458. }
  459. }
  460. #endregion
  461. #region 获取指定目录中所有文件列表
  462. /// <summary>
  463. /// 获取指定目录中所有文件列表
  464. /// </summary>
  465. /// <param name="directoryPath">指定目录的绝对路径</param>
  466. public static string[] GetFileNames(string directoryPath)
  467. {
  468. if (!IsExistDirectory(directoryPath))
  469. {
  470. throw new FileNotFoundException();
  471. }
  472. return Directory.GetFiles(directoryPath);
  473. }
  474. #endregion
  475. #region 获取指定目录中的子目录列表
  476. /// <summary>
  477. /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法
  478. /// </summary>
  479. /// <param name="directoryPath">指定目录的绝对路径</param>
  480. public static string[] GetDirectories(string directoryPath)
  481. {
  482. try
  483. {
  484. return Directory.GetDirectories(directoryPath);
  485. }
  486. catch { throw; }
  487. }
  488. /// <summary>
  489. /// 获取指定目录及子目录中所有子目录列表
  490. /// </summary>
  491. /// <param name="directoryPath">指定目录的绝对路径</param>
  492. /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
  493. /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
  494. /// <param name="isSearchChild">是否搜索子目录</param>
  495. public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
  496. {
  497. try
  498. {
  499. if (isSearchChild)
  500. {
  501. return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
  502. }
  503. else
  504. {
  505. return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
  506. }
  507. }
  508. catch { throw; }
  509. }
  510. #endregion
  511. #region 获取一个文件的长度
  512. /// <summary>
  513. /// 获取一个文件的长度,单位为Byte
  514. /// </summary>
  515. /// <param name="filePath">文件的绝对路径</param>
  516. public static int GetFileSize(string filePath)
  517. {
  518. //创建一个文件对象
  519. FileInfo fi = new FileInfo(filePath);
  520. //获取文件的大小
  521. return (int)fi.Length;
  522. }
  523. /// <summary>
  524. /// 获取一个文件的长度,单位为KB
  525. /// </summary>
  526. /// <param name="filePath">文件的路径</param>
  527. public static double GetFileSizeByKb(string filePath)
  528. {
  529. //创建一个文件对象
  530. FileInfo fi = new FileInfo(filePath);
  531. //获取文件的大小
  532. return Math.Round(Convert.ToDouble(filePath.Length) / 1024, 2);// ConvertHelper.ToDouble(ConvertHelper.ToDouble(fi.Length) / 1024, 1);
  533. }
  534. /// <summary>
  535. /// 获取一个文件的长度,单位为MB
  536. /// </summary>
  537. /// <param name="filePath">文件的路径</param>
  538. public static double GetFileSizeByMb(string filePath)
  539. {
  540. //创建一个文件对象
  541. FileInfo fi = new FileInfo(filePath);
  542. //获取文件的大小
  543. return Math.Round(Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024), 2);
  544. }
  545. #endregion
  546. #region 获取所有文件夹及子文件夹
  547. /// <summary>
  548. /// 获取所有文件夹及子文件夹
  549. /// </summary>
  550. /// <param name="dirPath"></param>
  551. /// <returns></returns>
  552. public static List<ArrayFiles> GetDirs(string dirPath)
  553. {
  554. var list = new List<ArrayFiles>();
  555. return GetArrys(dirPath, 0, list);
  556. }
  557. private static int zdId = 0;
  558. private static List<ArrayFiles> GetArrys(string dirPath, int pid, List<ArrayFiles> list)
  559. {
  560. if (!Directory.Exists(dirPath)) return list;
  561. if (Directory.GetDirectories(dirPath).Length <= 0) return list;
  562. foreach (string path in Directory.GetDirectories(dirPath))
  563. {
  564. zdId++;
  565. var model = new ArrayFiles()
  566. {
  567. Id = zdId,
  568. Name = path.Substring(path.LastIndexOf('\\') + 1, path.Length - (path.LastIndexOf('\\') + 1)),
  569. Pid = pid,
  570. Open = false,
  571. Target = "DeployBase",
  572. Url = "/FytAdmin/FileMiam/DocList?path=" + path
  573. };
  574. list.Add(model);
  575. GetArrys(path, model.Id, list);
  576. }
  577. return list;
  578. }
  579. public class ArrayFiles
  580. {
  581. public int Id { get; set; }
  582. public int Pid { get; set; }
  583. public string Name { get; set; }
  584. public Boolean Open { get; set; }
  585. public string Target { get; set; }
  586. public string Url { get; set; }
  587. }
  588. #endregion
  589. #region 将文件读取到字符串中
  590. /// <summary>
  591. /// 将文件读取到字符串中
  592. /// </summary>
  593. /// <param name="filePath">文件的绝对路径</param>
  594. public static string FileToString(string filePath)
  595. {
  596. return FileToString(filePath, Encoding.UTF8);
  597. }
  598. /// <summary>
  599. /// 将文件读取到字符串中
  600. /// </summary>
  601. /// <param name="filePath">文件的绝对路径</param>
  602. /// <param name="encoding">字符编码</param>
  603. public static string FileToString(string filePath, Encoding encoding)
  604. {
  605. //创建流读取器
  606. StreamReader reader = new StreamReader(filePath, encoding);
  607. try
  608. {
  609. //读取流
  610. return reader.ReadToEnd();
  611. }
  612. catch { throw; }
  613. finally
  614. {
  615. //关闭流读取器
  616. reader.Close();
  617. }
  618. }
  619. #endregion
  620. }
  621. /// <summary>
  622. /// 远程文件下载
  623. /// </summary>
  624. public class HttpDldFile
  625. {
  626. /// <summary>
  627. /// Http方式下载文件
  628. /// </summary>
  629. /// <param name="url">http地址</param>
  630. /// <param name="localfile">本地文件</param>
  631. /// <returns></returns>
  632. public bool Download(string url, string localfile)
  633. {
  634. bool flag = false;
  635. long startPosition = 0; // 上次下载的文件起始位置
  636. FileStream writeStream; // 写入本地文件流对象
  637. long remoteFileLength = GetHttpLength(url);// 取得远程文件长度
  638. //System.Console.WriteLine("remoteFileLength=" + remoteFileLength);
  639. if (remoteFileLength == 745)
  640. {
  641. System.Console.WriteLine("远程文件不存在.");
  642. return false;
  643. }
  644. // 判断要下载的文件夹是否存在
  645. if (File.Exists(localfile))
  646. {
  647. writeStream = File.OpenWrite(localfile); // 存在则打开要下载的文件
  648. startPosition = writeStream.Length; // 获取已经下载的长度
  649. if (startPosition >= remoteFileLength)
  650. {
  651. System.Console.WriteLine("本地文件长度" + startPosition + "已经大于等于远程文件长度" + remoteFileLength);
  652. writeStream.Close();
  653. return false;
  654. }
  655. else
  656. {
  657. writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
  658. }
  659. }
  660. else
  661. {
  662. writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
  663. startPosition = 0;
  664. }
  665. try
  666. {
  667. HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
  668. if (startPosition > 0)
  669. {
  670. myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
  671. }
  672. Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
  673. byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
  674. int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次
  675. long currPostion = startPosition;
  676. while (contentSize > 0)// 如果读取长度大于零则继续读
  677. {
  678. currPostion += contentSize;
  679. int percent = (int)(currPostion * 100 / remoteFileLength);
  680. System.Console.WriteLine("percent=" + percent + "%");
  681. writeStream.Write(btArray, 0, contentSize);// 写入本地文件
  682. contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
  683. }
  684. //关闭流
  685. writeStream.Close();
  686. readStream.Close();
  687. flag = true; //返回true下载成功
  688. }
  689. catch (Exception)
  690. {
  691. writeStream.Close();
  692. flag = false; //返回false下载失败
  693. }
  694. return flag;
  695. }
  696. // 从文件头得到远程文件的长度
  697. private static long GetHttpLength(string url)
  698. {
  699. long length = 0;
  700. try
  701. {
  702. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
  703. HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
  704. if (rsp.StatusCode == HttpStatusCode.OK)
  705. {
  706. length = rsp.ContentLength;// 从文件头得到远程文件的长度
  707. }
  708. rsp.Close();
  709. return length;
  710. }
  711. catch (Exception e)
  712. {
  713. var s = e.Message;
  714. return length;
  715. }
  716. }
  717. }
  718. }