/// <summary> /// 下载 /// </summary> /// <param name="config">配置</param> /// <param name="fileurl">源文件地址</param> /// <param name="hash">哈希</param> /// <param name="ext">扩展名</param> /// <param name="isevent">是否订阅事件</param> /// <returns></returns> public async Task Download(XConfig config, string fileurl, string hash, string ext, bool isevent = false) { try { WebClient client = new WebClient { Headers = { ["Hash"] = hash } }; if (isevent) { client.DownloadProgressChanged += OnChanged; client.DownloadFileCompleted += OnFinished; } string filename = config.SavePath.EndsWith(@"\") ? config.SavePath + hash + (ext.Contains(".")? ext:"." + ext) : config.SavePath + @"\" + hash + (ext.Contains(".") ? ext : "." + ext); await client.DownloadFileTaskAsync(new Uri(fileurl), filename); } catch (Exception e) { await Task.Delay(1000); } }
/// <summary> /// 写入配置 /// </summary> /// <param name="data">配置参数</param> public static async Task WriteConfig(XConfig data) { try { JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Include }; var json = JsonConvert.SerializeObject(data, settings); string path = AppDomain.CurrentDomain.BaseDirectory + @"config.json"; using (var file = new FileStream(path, FileMode.Truncate, FileAccess.ReadWrite)) { using (var writer = new StreamWriter(file, Encoding.UTF8)) { using (var jsonwriter = new JsonTextWriter(writer)) { await jsonwriter.WriteRawAsync(json); } } } } catch (Exception) { await Task.Delay(300); } }
/// <summary> /// 读取配置 /// </summary> /// <returns></returns> public static async Task <XConfig> ReadConfig() { try { string path = AppDomain.CurrentDomain.BaseDirectory + "config.json"; if (!File.Exists(path)) { JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Include }; XConfig data = new XConfig { SavePath = AppDomain.CurrentDomain.BaseDirectory + "Douyin", IsDownloadVoice = true, IsDownloadPoster = false }; var json = JsonConvert.SerializeObject(data, settings); using (var file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) { using (var writer = new StreamWriter(file, Encoding.UTF8)) { using (var jsonwriter = new JsonTextWriter(writer)) { await jsonwriter.WriteRawAsync(json); } } } return(data); } using (var file = new FileStream(path, FileMode.Open, FileAccess.Read)) { using (var reader = new StreamReader(file, Encoding.UTF8)) { var json = await reader.ReadToEndAsync(); return(JsonConvert.DeserializeObject <XConfig>(json)); } } } catch (Exception) { return(null); } }