// 将tasks保存到二进制文件中 public Boolean saveToFile(String file) { try { if (tasks.Count==0) { // 没任务就不存 return false; } if (File.Exists(file)) { // 原有文件删掉 File.Delete(file); } // 写文件 FileStream writeStream = new FileStream(file, FileMode.Create); BinaryWriter bw = new BinaryWriter(writeStream); foreach (Dld tt in tasks) { bw.Write((String)tt.getID());// 以下强制类型转换并非必要,而是为了阅读时辨别类型 bw.Write((String)tt.getFilename()); bw.Write((String)tt.getUrl()); bw.Write((long)tt.getRemoteFileSize()); bw.Write((String)tt.getPercent()); bw.Write((String)tt.getStatus()); bw.Write((String)tt.getType()); bw.Flush(); } bw.Close(); writeStream.Close(); return true; }catch(Exception e){ throw e; } } // 从二进制文件中提取tasks public Boolean loadFromFile(String file) { try { if (File.Exists(file)==false) { // 文件不存在直接返回 return false; } // 读文件 FileStream readStream = new FileStream(file, FileMode.Open); BinaryReader br = new BinaryReader(readStream); try { while(true) {
// 读取过程正好是写入过程的逆序 String id = br.ReadString(); String filename = br.ReadString(); String url = br.ReadString(); long remoteFileSize = br.ReadInt64(); String percent = br.ReadString(); String status = br.ReadString(); String type = br.ReadString(); // 这个地方要根据类型判断 Dld tnew = null; if (type.Equals("http")) { tnew = new HttpDld(mainGui, id, filename, url, remoteFileSize, type); } else if (type.Equals("ftp")) { tnew = new FtpDld(mainGui, id, filename, url, remoteFileSize, type); } tnew.setStatus(status); tnew.setPercent(percent); tasks.Add(tnew); }; } catch(EndOfStreamException ex){// 读完会抛出这个异常,正常过程 System.Console.WriteLine("文件" + file + "读取完毕,读取任务" + tasks.Count+"条."); } br.Close(); readStream.Close(); return true; } catch (Exception e) { throw e; } }