private static void UpdatePaths() { var pathList = new List <FilePaths>(); using (TextReader reader = File.OpenText(pathsFile)) { var pattern = new Regex("[/\"]|[/]{2}"); while (reader.Peek() >= 0) { var line = reader.ReadLine(); if (!string.IsNullOrWhiteSpace(line)) { line = pattern.Replace(line, "/").ToLower(); try { Path.GetFullPath(line); var lineMD5 = MD5Tools.CreateMD5(line); line = line.Replace("/", "\\"); pathList.Add(new FilePaths(line, lineMD5)); } catch { } } } } pathsArray = pathList.ToArray(); }
/// <summary> /// 将分块续传的文件释放出来并删除分块续传文件 /// </summary> /// <returns></returns> public async Task <bool> Release() { string filePath = this.downloadPartPath.Replace(DownloadFile.Ext, string.Empty); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } using (FileStream write = System.IO.File.Create(filePath)) { this.fileStream.Position = this.Position; await this.fileStream.CopyToAsync(write); } //校验服务器上的md5 如果服务器上下载数据不包含md5则视为md5校验通过 if (this.MD5 == null || this.MD5 == MD5Tools.GetFileMd5(filePath)) { this.fileStream?.Dispose(); System.IO.File.Delete(this.downloadPartPath); return(true); } else { System.IO.File.Delete(filePath); return(false); } }
public Task <bool> CreateAsync(UserDto dto) { return(Task <bool> .Factory.StartNew(() => { try { User user = _mapper.Map <User>(dto); _logger.LogDebug(JsonConvert.SerializeObject(user)); var pwmd5 = MD5Tools.MD5Encrypt32(dto.Password); var scmd5 = Guid.NewGuid().ToString("N"); var pwdHash = MD5Tools.MD5Encrypt64(pwmd5 + scmd5); user.PasswordHash = pwdHash; user.SecurityCode = scmd5; _userRepository.Add(user); int count = _unitOfWork.SaveChanges(); _logger.LogDebug("保存成功" + count); } catch (System.Exception ex) { _logger.LogError(ex.Message); return false; } return true; })); }
/// <summary> /// /// </summary> /// <param name="uri"></param> /// <returns></returns> public async void Download(string filePath) { bool success = false; string downloadPartPath = Path.Combine(filePath + ".downloadPart"); string url = this.DownloadUrl + "?fileName=" + Path.GetFileName(filePath); using (FileStream fileStream = File.Create(downloadPartPath)) using (HttpClient httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) }) { try { httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, null); HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); long?contentLength = httpResponseMessage.Content.Headers.ContentLength; if (httpResponseMessage.Content.Headers.ContentRange != null) //如果为空,则说明服务器不支持断点续传 { contentLength = httpResponseMessage.Content.Headers.ContentRange.Length; //服务器上的文件大小 } string md5 = httpResponseMessage.Content.Headers.ContentMD5 == null ? null : Convert.ToBase64String(httpResponseMessage.Content.Headers.ContentMD5); Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync(); stream.ReadTimeout = 10 * 1000; DownloadFile downloadFile = new DownloadFile() { Length = contentLength, MD5 = md5, RangeBegin = 0, URL = url }; await Download(stream, fileStream, downloadFile); if (md5 == null || md5 == MD5Tools.GetFileMd5(downloadPartPath)) { success = true; } } catch (Exception ex) { this.OnDownloadError(ex.Message); } } if (success) { try { File.Move(downloadPartPath, filePath); } catch (Exception ex) { this.OnDownloadError(ex.Message); } } this.OnDownloadCompleted(success); }
public static AudioClip Load(AudioKey InAudioKey) { #if UNITY_EDITOR // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (!AudioConfig.USE_ASSET_BUNDLE_IN_EDITOR_B) { if (_keyForFullname == null) { DirectoryInfo directoryInfo = new DirectoryInfo("Assets/Bundle/Audio"); FileInfo[] files = directoryInfo.GetFiles(); int count = files.Length; _keyForFullname = new Dictionary <string, string>(count); for (int i = 0; i < count; i++) { if (files[i].Extension == ".meta") { continue; } string fullname = files[i].Name; _keyForFullname.Add(Path.GetFileNameWithoutExtension(fullname), fullname); } } if (_keyForFullname.TryGetValue(InAudioKey.ToString(), out var filename)) { return(UnityEditor.AssetDatabase.LoadAssetAtPath <AudioClip>(Path.Combine("Assets/Bundle/Audio/", filename))); } Debug.LogError($"Audio clip named '{InAudioKey}' not found in ."); return(null); } #endif string fileName = InAudioKey.ToString(); string bundleName = fileName.ToLower(); string localPath = UnityPathTools.GetPersistentDataPath( $"b22f0418e8ac915eb66f829d262d14a2/{MD5Tools.GetStringMd5(bundleName)}"); string streamPath = UnityPathTools.GetStreamingAssetsPath($"Audio/{MD5Tools.GetStringMd5(bundleName)}"); AssetBundle ab = AssetBundle.LoadFromFile(File.Exists(localPath) ? localPath : streamPath); if (ab == null) { return(null); } AudioClip ac = ab.LoadAsset <AudioClip>(fileName); ab.Unload(false); return(ac); }
public Word(string literal) { if (string.IsNullOrWhiteSpace(literal)) { throw new ArgumentNullException(); } Literal = literal.Trim(); Id = MD5Tools.Generate(Literal); }
public FileScan(string dir, string name, bool calcMD5 = true) { this.FullPath = Path.Combine(dir, name); this.Length = new FileInfo(this.FullPath).Length; this.Version = System.Diagnostics.FileVersionInfo.GetVersionInfo(this.FullPath).ProductVersion; this.Name = name; if (calcMD5) { this.MD5 = MD5Tools.GetFileMd5(this.FullPath); } }
public void OnPreprocessBuild(BuildTarget InTarget, string InPath) { string streamingAssetsPath = Application.streamingAssetsPath; if (!Directory.Exists(streamingAssetsPath)) { return; } List <FileInfo> fileInfos = FileTools.GetAllFileInfos(streamingAssetsPath); if (null == fileInfos) { return; } List <FileInfo> dbFileInfos = new List <FileInfo>(); int count = fileInfos.Count; for (int i = 0; i < count; i++) { if (fileInfos[i].Extension == ".db") { dbFileInfos.Add(fileInfos[i]); } } SQLite3Data data = Resources.Load <SQLite3Data>("Sqlite3Data"); string dataPath = AssetDatabase.GetAssetPath(data); data = ScriptableObject.CreateInstance <SQLite3Data>(); int dbCount = dbFileInfos.Count; data.AllData = new List <SQLite3SingleData>(dbCount); for (int i = 0; i < dbCount; i++) { SQLite3SingleData singleData = new SQLite3SingleData { Name = dbFileInfos[i].Name, LocalName = MD5Tools.GetStringMd5(dbFileInfos[i].Name), Md5 = MD5Tools.GetFileMd5(dbFileInfos[i].FullName) }; string dirPath = dbFileInfos[i].DirectoryName; singleData.Directory = string.IsNullOrEmpty(dirPath) || dirPath == streamingAssetsPath ? string.Empty : dirPath.Replace('\\', '/').Replace(streamingAssetsPath, string.Empty); data.AllData.Add(singleData); } AssetDatabase.CreateAsset(data, dataPath); AssetDatabase.SaveAssets(); }
public Task <ClaimsIdentity> LoginAsync(LoginDto dto) { User user = _userRepository.Query.FirstOrDefault(f => f.Email == dto.Account || f.Phone == dto.Account || f.UserName == dto.Account); if (user == null) { return(Task.FromResult <ClaimsIdentity>(null)); } string pwmd5 = MD5Tools.MD5Encrypt32(dto.Password); string pwdHash = MD5Tools.MD5Encrypt64(pwmd5 + user.SecurityCode); if (pwdHash == user.PasswordHash) { return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(dto.Account, "Token"), new Claim[] { }))); } return(Task.FromResult <ClaimsIdentity>(null)); }
private static void WriteVersion(string InStreamPath) { FileInfo[] buildFileInfos = new DirectoryInfo(InStreamPath).GetFiles(); int len = buildFileInfos.Length; List <BuildInfo> buildInfos = new List <BuildInfo>(); for (int i = 0; i < len; ++i) { if (buildFileInfos[i].Extension == ".manifest" || buildFileInfos[i].Extension == ".meta") { buildFileInfos[i].Delete(); continue; } if (buildFileInfos[i].Name == "Audio") { buildFileInfos[i].Delete(); continue; } buildInfos.Add(new BuildInfo(buildFileInfos[i].Name, MD5Tools.GetFileMd5(Path.Combine(InStreamPath, buildFileInfos[i].Name)))); } using (FileStream fs = new FileStream(Path.Combine(InStreamPath, "45264b0d287afd9795f479a7882b3765"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { using (StreamWriter sw = new StreamWriter(fs)) { foreach (BuildInfo buildInfo in buildInfos) { sw.WriteLine(buildInfo.ToString()); } sw.Flush(); sw.Close(); } fs.Close(); } }
private void Login(string input_username, string input_passwd) { Console.WriteLine("username is " + input_username + " ,password is " + input_passwd); Console.WriteLine("remember is " + remember_username.ToString()); Console.WriteLine("auto is " + auto_login.ToString()); string crypted_passwd = MD5Tools.GetMD5(input_passwd); int port = int.Parse(ConfigurationManager.AppSettings["network_port"]); string ip = ConfigurationManager.AppSettings["network_ip"]; if (!NetworkClient.GetIsConnected()) { NetworkClient.StartNetwork(ip, port); } NetworkClient.network.LoginRequest(input_username, crypted_passwd); while (ClientInfo.login_state != ClientInfo.LoginState.login_success) { if (ClientInfo.login_state == ClientInfo.LoginState.log_error) { MessageBox.Show("登录错误,请检查用户名、密码是否正确!"); ClientInfo.login_state = ClientInfo.LoginState.not_logged_in; Dispatcher.BeginInvoke(new Action(() => { LoadGrid.Visibility = Visibility.Collapsed; login_timer.last_req_time = 0; login_timer.timer.Stop(); })); return; } Thread.Sleep(10); } ClientInfo.self_user.userState = User.user_state.free; ClientInfo.self_user.username = input_username; Dispatcher.BeginInvoke(new Action(() => { ClientInfo.hall = new HallWindow(); ClientInfo.hall.Show(); login_timer.last_req_time = 0; login_timer.timer.Stop(); Close(); LoadGrid.Visibility = Visibility.Collapsed; })); }
private static void BuildAudio() { string streamPath = Path.Combine(Application.streamingAssetsPath, EditorUserBuildSettings.activeBuildTarget.ToString(), "Audio"); if (Directory.Exists(streamPath)) { Directory.Delete(streamPath, true); } Directory.CreateDirectory(streamPath); DirectoryInfo dirInfo = new DirectoryInfo(AudioConfig.AUDIO_RES_ASSETS_PATH_S); FileInfo[] infos = dirInfo.GetFiles(); int length = infos.Length; AssetBundleBuild[] levelDataList = new AssetBundleBuild[length]; for (int i = 0; i < length; i++) { if (infos[i].Extension.Equals(".meta")) { continue; } string filename = Path.GetFileNameWithoutExtension(infos[i].Name).ToLower(); AssetImporter importer = AssetImporter.GetAtPath(Path.Combine(AudioConfig.AUDIO_RES_ASSETS_PATH_S, infos[i].Name)); importer.assetBundleName = filename; levelDataList[i] = new AssetBundleBuild { assetBundleName = MD5Tools.GetStringMd5(filename), assetNames = new[] { importer.assetPath } }; } BuildPipeline.BuildAssetBundles(streamPath, levelDataList, BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget); WriteVersion(streamPath); AssetDatabase.Refresh(); EditorUtility.DisplayDialog("Tips", "Build audio asset bundle completed.", "ok"); }
public override void OnHandlerMessage(OperationRequest request, OperationResponse response, ClientPeer peer, SendParameters sendParameters) { User user = ParameterTool.GetParameter <User>(request.Parameters, ParameterCode.User); User userDB = manager.GetUserByUsername(user.Username); if (userDB != null) { response.ReturnCode = (short)ReturnCode.Fall; response.DebugMessage = "用户名重复"; } else { user.Password = MD5Tools.GetMD5(user.Password); response.ReturnCode = (short)ReturnCode.Success; manager.AddUser(user); } }
public override void OnHandlerMessage(OperationRequest request, OperationResponse response, ClientPeer peer, SendParameters sendParameters) { Dictionary <byte, object> parameters = request.Parameters; object userObj = null; parameters.TryGetValue((byte)ParameterCode.User, out userObj); User user = JsonMapper.ToObject <User>(userObj.ToString()); //由名字得到数据库中的user对象 User userDB = manager.GetUserByUsername(user.Username); //数据库中存在对象,并且密码输入正确 if (userDB != null && userDB.Password == MD5Tools.GetMD5(user.Password)) { //登录取得成功 response.ReturnCode = (short)ReturnCode.Success; peer.LoginUser = userDB; } else { response.ReturnCode = (short)ReturnCode.Fall; response.DebugMessage = "用户名或密码错误"; } }
public void It_can_generate_correct_MD5_of_a_string(string input, string expected) { var actual = MD5Tools.Generate(input); Assert.Equal(expected, actual, true); }
public static void ProcessFile(string file) { currentFile = file; var fileName = Path.GetFileName(file); Console.WriteLine($"Processing {fileName}..."); if (!File.Exists(file)) { WarningMessage("File does not exist. Skipping..."); return; } var ext = Path.GetExtension(file).ToLower(); if ((games.HasFlag(Games.BBCT) || games.HasFlag(Games.BBCSEX) || games.HasFlag(Games.BBCPEX)) && ext != ".pac") { InfoMessage("Specified game only obfuscates .pac files. Skipping..."); return; } if (games.HasFlag(Games.BBTAG) && !BBTAGObfuscatedFiles.Contains(ext)) { InfoMessage($"Specified game does not obfuscate {ext} files. Skipping..."); return; } if (ext == ".pacgz" && !modes.HasFlag(Modes.SwitchDeflate) && !modes.HasFlag(Modes.SwitchInflate) && !modes.HasFlag(Modes.Auto)) { InfoMessage($"Specified game and mode does not obfuscate {ext} files. Skipping..."); return; } if (string.IsNullOrWhiteSpace(ext) && (modes.HasFlag(Modes.SwitchDeflate) || modes.HasFlag(Modes.SwitchInflate))) { InfoMessage("Specified game and mode does not obfuscate empty exetension files. Skipping..."); return; } byte[] fileBytes = null; var fileDirectory = outputPath; var magicBytes = new byte[4]; using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { fs.Read(magicBytes, 0, 4); fs.Close(); } var isPACMB = magicBytes.SequenceEqual(new byte[] { 0x46, 0x50, 0x41, 0x43 }); var isHIPMB = magicBytes.SequenceEqual(new byte[] { 0x48, 0x49, 0x50, 0x00 }); var isHPLMB = magicBytes.SequenceEqual(new byte[] { 0x48, 0x50, 0x41, 0x4C }); var fileIsKnown = isPACMB || isHIPMB || isHPLMB; if (modes == Modes.Auto || (games == Games.BBCSEX || games == Games.BBCPEX) && modes == 0) { if (magicBytes.SequenceEqual(new byte[] { 0x44, 0x46, 0x41, 0x53 })) { modes = Modes.Inflate; } } if (modes == Modes.Auto || games == Games.BBTAG && modes == 0) { if (magicBytes.Take(3).SequenceEqual(new byte[] { 0x1F, 0x8B, 0x08 })) { modes = Modes.SwitchInflate; } else if (MD5Tools.IsMD5(fileName)) { modes = Modes.MD5Decrypt; } else if (fileName.Length > 32 && MD5Tools.IsMD5(fileName.Substring(0, 32))) { modes = Modes.MD5Encrypt; } } if (modes == Modes.Auto || games != 0 && modes == 0) { switch (games) { case Games.BBCT: modes = fileIsKnown ? Modes.Encrypt : Modes.Decrypt; break; case Games.BBTAG: modes = fileIsKnown ? Modes.MD5Encrypt : Modes.MD5Decrypt; break; case Games.BBCSEX: case Games.BBCPEX: case 0: modes = fileIsKnown ? Modes.Deflate | Modes.Encrypt : Modes.Inflate | Modes.Decrypt; break; } } if (modes == Modes.Auto || fileIsKnown && (modes.HasFlag(Modes.Decrypt) || modes.HasFlag(Modes.MD5Decrypt) || modes.HasFlag(Modes.Inflate) || modes.HasFlag(Modes.SwitchInflate))) { var pacFile = new PACFileInfo(file); if (pacFile.IsValidPAC) { fileBytes = pacFile.GetBytes(); } else { var hipFile = new HIPFileInfo(file); if (hipFile.IsValidHIP) { fileBytes = pacFile.GetBytes(); } else { var hplFile = new HPLFileInfo(file); if (hplFile.IsValidHPL) { fileBytes = pacFile.GetBytes(); } } } } if (fileBytes == null) { var changed = false; var memStream = new MemoryStream(); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { fs.CopyTo(memStream); } if (modes.HasFlag(Modes.Deflate)) { memStream.Position = 0; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"Deflating {fileName}..."); var ms = BBObfuscatorTools.DFASFPACDeflateStream(memStream); memStream.Close(); memStream.Dispose(); memStream = ms; changed = true; } else if (modes.HasFlag(Modes.Decrypt)) { memStream.Position = 0; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Decrypting {fileName}..."); var ms = BBObfuscatorTools.FPACCryptStream(memStream, file, CryptMode.Decrypt); memStream.Close(); memStream.Dispose(); memStream = ms; changed = true; } if (modes.HasFlag(Modes.Encrypt)) { memStream.Position = 0; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Encrypting {fileName}..."); var ms = BBObfuscatorTools.FPACCryptStream(memStream, file, CryptMode.Encrypt); memStream.Close(); memStream.Dispose(); memStream = ms; changed = true; } else if (modes.HasFlag(Modes.Inflate)) { memStream.Position = 0; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"Inflating {fileName}..."); var ms = BBObfuscatorTools.DFASFPACInflateStream(memStream); memStream.Close(); memStream.Dispose(); memStream = ms; changed = true; } else if (modes.HasFlag(Modes.MD5Encrypt)) { memStream.Position = 0; if (fileName.Length > 32 && MD5Tools.IsMD5(fileName.Substring(0, 32)) || file.LastIndexOf("data") >= 0) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"MD5 Encrypting {fileName}..."); var ms = BBTAGMD5CryptTools.BBTAGMD5CryptStream(memStream, file, CryptMode.Encrypt); memStream.Close(); memStream.Dispose(); memStream = ms; if (fileName.Length > 32 && MD5Tools.IsMD5(fileName.Substring(0, 32))) { fileName = fileName.Substring(0, 32); } else if (!MD5Tools.IsMD5(fileName)) { var lastIndex = file.LastIndexOf("data"); var datapath = file.Substring(lastIndex, file.Length - lastIndex); fileName = MD5Tools.CreateMD5(datapath.Replace("\\", "/")); file = fileName; } changed = true; } else { WarningMessage( "File's name and/or directory does not follow the rules for MD5 Encryption. Ignoring..."); } } else if (modes.HasFlag(Modes.MD5Decrypt)) { memStream.Position = 0; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"MD5 Decrypting {fileName}..."); var ms = BBTAGMD5CryptTools.BBTAGMD5CryptStream(memStream, file, CryptMode.Decrypt); memStream.Close(); memStream.Dispose(); memStream = ms; if (MD5Tools.IsMD5(fileName)) { if (!string.IsNullOrWhiteSpace(pathsFile)) { var length = pathsArray.Length; for (var i = 0; i < length; i++) { if (pathsArray[i].filepathMD5 == fileName) { var filepath = pathsArray[i].filepath; fileName = Path.GetFileName(filepath); fileDirectory = Path.Combine(outputPath, Path.GetDirectoryName(filepath)); } } } if (MD5Tools.IsMD5(fileName)) { fileName = fileName + "_" + StringToByteArray(fileName)[7] % 43; } } changed = true; } else if (modes.HasFlag(Modes.SwitchDeflate)) { memStream.Position = 0; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"Switch Deflating {fileName}..."); var output = new MemoryStream(); var data = memStream.ToArray(); using (Stream input = new GZipStream(output, CompressionLevel.Optimal, true)) { input.Write(data, 0, data.Length); input.Close(); } memStream.Close(); memStream.Dispose(); memStream = output; changed = true; if (ext == ".pac") { fileName = Path.GetFileNameWithoutExtension(fileName) + ".pacgz"; } } else if (modes.HasFlag(Modes.SwitchInflate)) { memStream.Position = 0; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"Switch Inflating {fileName}..."); using (Stream input = new GZipStream(new MemoryStream(memStream.GetBuffer()), CompressionMode.Decompress, true)) { using (var output = new MemoryStream()) { input.CopyTo(output); input.Close(); memStream.Close(); memStream.Dispose(); memStream = new MemoryStream(output.ToArray()); } } changed = true; if (ext == ".pacgz") { fileName = Path.GetFileNameWithoutExtension(fileName) + ".pac"; } } Console.ForegroundColor = ConsoleColor.White; if (changed) { fileBytes = memStream.ToArray(); } memStream.Close(); memStream.Dispose(); } if (fileBytes == null) { var automaticString = modes == Modes.Auto || games != 0 && modes == 0 ? " automatically" : string.Empty; WarningMessage($"Could not{automaticString} process {fileName}."); return; } var directory = initFilePath == file || file == fileName ? fileDirectory : Path.Combine(fileDirectory, Path.GetDirectoryName(file).Replace(initFilePath, string.Empty)); Directory.CreateDirectory(directory); var filePath = Path.GetFullPath(Path.Combine(directory, fileName)); if (File.Exists(filePath) && !options.HasFlag(Options.Replace)) { var backupPath = filePath + ".bak"; if (File.Exists(backupPath)) { File.Delete(backupPath); } File.Move(filePath, backupPath); } File.WriteAllBytes(filePath, fileBytes); Console.Write("Finished processing "); var resultFileConsoleColor = ConsoleColor.White; if ((modes.HasFlag(Modes.Encrypt) || modes.HasFlag(Modes.MD5Encrypt)) && modes.HasFlag(Modes.Deflate)) { resultFileConsoleColor = ConsoleColor.Magenta; } else if (modes.HasFlag(Modes.Deflate)) { resultFileConsoleColor = ConsoleColor.Cyan; } else if (modes.HasFlag(Modes.Encrypt) || modes.HasFlag(Modes.MD5Encrypt)) { resultFileConsoleColor = ConsoleColor.Green; } Console.ForegroundColor = resultFileConsoleColor; Console.Write($"{fileName}"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("."); }
public UpdateInfo GetUpdateInfo(string content) { UpdateInfo info = new UpdateInfo(); string[] files = content.Split('\n'); string random = DateTime.Now.ToString("yyyymmddhhmmss"); for (int i = 0; i < files.Length; i++) { //优先判断是否存在于datapath,如果存在则读取,不存在尝试读取streamingassts目录 if (string.IsNullOrEmpty(files[i])) { continue; } string[] keyValue = files[i].Split('|'); string f = keyValue[0]; string dataLocalFile = (PathTools.DataPath + f).Trim(); string localfile = dataLocalFile; string path = Path.GetDirectoryName(localfile); if (!Directory.Exists(path)) { string contentLocalFile = (PathTools.AppContentPath() + f).Trim(); string contentpath = Path.GetDirectoryName(contentLocalFile); if (!Directory.Exists(contentpath)) { Directory.CreateDirectory(path); } else { localfile = contentLocalFile; } } string fileUrl = url + f + "?v=" + random; bool canUpdate = !File.Exists(localfile); //本地存在文件 if (!canUpdate) { string remoteMd5 = keyValue[1].Trim(); string localMd5 = MD5Tools.md5file(localfile); canUpdate = !remoteMd5.Equals(localMd5); if (canUpdate) { File.Delete(localfile); } } //本地缺少文件 if (canUpdate) { if (fileUrl.Contains(AppConst.DllName) && Application.platform == RuntimePlatform.Android) { info.bRestart = true; } if (!fileUrl.Contains("manifest")) { info.totalSize += GetHttpFileSize(fileUrl); } UnityTools.LogMust("需要更新:" + fileUrl); info.dict[dataLocalFile] = fileUrl; } } return(info); }
public string SyncFiles() { //添加或更新文件 int errorCount = 0; int insertCount = 0; int updateCount = 0; List <FileInfo> ls = new List <FileInfo>(); ls = GetAllDirectoriesFiles(); //ls = FilterSupportedFiles(ls); SqliteHelper sqlHelper = new SqliteHelper(); //保存最新的所有文件 sqlHelper.ExecuteNonQuery($"delete from LatestFiles"); foreach (var f in ls) { try { if (f.FullName.Contains("'") == false) { string fileMD5 = MD5Tools.GetMD5(f.FullName); sqlHelper.ExecuteNonQuery($"insert into LatestFiles(md5,fullname) values('{fileMD5}','{f.FullName}')"); } } catch { errorCount += 1; } } //删除过期的文件 sqlHelper.ExecuteNonQuery($"delete from files where md5 not in (select md5 from LatestFiles)"); foreach (var f in ls) { try { //排除含有'符号的文件,否则插入数据库会出错 if (f.FullName.Contains("'") == false || f.FullName.Contains("~") == false) { string fileMD5 = MD5Tools.GetMD5(f.FullName); string fileModifiedtime = f.LastWriteTime.ToString(); //如果数据库中不存在,直接添加 if (sqlHelper.ExecuteScalar($"select count(MD5) from Files where MD5='{fileMD5}'") != 1) { sqlHelper.ExecuteNonQuery($"insert into Files(MD5,fullname,modifiedtime,gettime) values('{fileMD5}','{f.FullName}','{fileModifiedtime}','{DateTime.Now}')"); insertCount = insertCount + 1; } else { //如果数据库中存在,但是修改日期不一样,先删除,后添加 if (sqlHelper.ExecuteScalar($"select count(MD5) from Files where MD5='{fileMD5}' and modifiedtime<>'{fileModifiedtime}'") == 1) { sqlHelper.ExecuteNonQuery($"delete from Files where MD5='{fileMD5}'"); sqlHelper.ExecuteNonQuery($"insert into Files(MD5,fullname,modifiedtime,gettime) values('{fileMD5}','{f.FullName}','{fileModifiedtime}','{DateTime.Now}')"); updateCount = updateCount + 1; } } } } catch { errorCount = errorCount + 1; } } int total = sqlHelper.ExecuteScalar("select count(*) from files"); return("索引文件共计:" + total.ToString() + ",新增:" + insertCount.ToString() + ",更新:" + updateCount.ToString() + ",错误:" + errorCount.ToString()); }
/// <summary> /// 断点续传下载 /// </summary> /// <param name="uri"></param> /// <returns></returns> public async void ResumeDownload(string partPath) { bool success = false; using (FileStream fileStream = System.IO.File.Open(partPath, FileMode.Open)) using (HttpClient httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) }) { DownloadFile downloadFile = DownloadFile.FromFileStream(fileStream); if (downloadFile == null) //为空说明已经完成 { success = true; } else { try { httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(downloadFile.RangeBegin, null); HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(downloadFile.URL, HttpCompletionOption.ResponseHeadersRead); long?contentLength = httpResponseMessage.Content.Headers.ContentLength; if (httpResponseMessage.Content.Headers.ContentRange != null) //如果为空,则说明服务器不支持断点续传 { contentLength = httpResponseMessage.Content.Headers.ContentRange.Length; //服务器上的文件大小 } string md5 = httpResponseMessage.Content.Headers.ContentMD5 == null ? null : Convert.ToBase64String(httpResponseMessage.Content.Headers.ContentMD5); if (md5 != downloadFile.MD5) { throw new Exception("服务器的上的版本已经变化"); } Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync(); stream.ReadTimeout = 10 * 1000; await Download(stream, fileStream, downloadFile); if (fileStream.Length == downloadFile.Length) { if (md5 == null || md5 == MD5Tools.GetFileMd5(partPath)) { success = true; } } else { success = false; } } catch (Exception ex) { //请求错误 this.OnDownloadError(new ErrorArgs(ex.Message)); } } } if (success) { try { System.IO.File.Move(partPath, partPath.Replace(".downloadPart", "")); } catch (Exception ex) { this.OnDownloadError(new ErrorArgs(ex.Message)); } } this.OnDownloadCompleted(new CompletedArgs(success)); }