Exemplo n.º 1
0
        /// <summary>
        /// 写入安全 JSON。
        /// </summary>
        /// <param name="combiner">给定的 <see cref="FilePathCombiner"/>。</param>
        /// <param name="value"></param>
        /// <param name="encoding">给定的 <see cref="Encoding"/>(可选)。</param>
        /// <param name="settings">给定的 <see cref="JsonSerializerSettings"/>(可选)。</param>
        /// <param name="autoCreateDirectory">自动创建目录(可选;默认启用)。</param>
        /// <returns>返回 JSON 字符串。</returns>
        public static string WriteSecureJson(this FilePathCombiner combiner, object value, Encoding encoding = null,
                                             JsonSerializerSettings settings = null, bool autoCreateDirectory = true)
        {
            var json = JsonConvert.SerializeObject(value, settings);

            if (autoCreateDirectory)
            {
                combiner.CreateDirectory();
            }

            if (combiner.Exists())
            {
                combiner.Delete(); // 防止混合现有文件内容
            }
            if (encoding.IsNull())
            {
                encoding = ExtensionSettings.Preference.DefaultEncoding;
            }

            using (var fs = File.OpenWrite(combiner))
                using (var bw = new BinaryWriter(fs, encoding))
                {
                    var buffer = json.FromEncodingString(encoding);
                    bw.Write(buffer.AsAes());
                }

            return(json);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 写入所有文本。
        /// </summary>
        /// <param name="combiner">给定的 <see cref="FilePathCombiner"/>。</param>
        /// <param name="contents">给定的内容集合。</param>
        /// <param name="encoding">给定的 <see cref="Encoding"/>(可选)。</param>
        /// <param name="autoCreateDirectory">自动创建目录(可选;默认启用)。</param>
        public static void WriteAllText(this FilePathCombiner combiner, string contents,
                                        Encoding encoding = null, bool autoCreateDirectory = true)
        {
            if (autoCreateDirectory)
            {
                combiner.CreateDirectory();
            }

            File.WriteAllText(combiner, contents, encoding ?? ExtensionSettings.Preference.DefaultEncoding);
        }