/// <summary> /// Formats the specified JSON file and overwrites it if necessary. /// </summary> /// <exception cref="ArgumentNullException"> /// path is null. /// </exception> /// <exception cref="IOException"> /// path is invalid. /// </exception> public static bool FormatFile(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } var srcFile = PathEx.Combine(path); if (!PathEx.IsValidPath(srcFile)) { throw new IOException(); } var srcDir = Path.GetDirectoryName(srcFile); var newFile = PathEx.GetUniquePath(srcDir, "tmp", ".json"); using (var sr = new StreamReader(srcFile)) { using var fs = new FileStream(newFile, FileMode.Create); int count; var ca = new char[4096]; var depth = 0; var isEscape = false; var isValue = false; while ((count = sr.Read(ca, 0, ca.Length)) > 0) { Format(fs, ca, count, ' ', ref depth, ref isEscape, ref isValue); } } if (!FileEx.ContentIsEqual(srcFile, newFile)) { return(FileEx.Move(newFile, srcFile, true)); } FileEx.TryDelete(newFile); return(false); }
/// <summary> /// Returns the current user's temporary path in combination with unique name /// starting with 'tmp' prefix, followed by a hash of the specified length. /// </summary> /// <param name="hashLen"> /// The length of the hash. Valid values are 4 through 24. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// hashLen is not between 4 and 24. /// </exception> public static string GetUniqueTempPath(int hashLen) => PathEx.GetUniquePath("%TEMP%", "tmp", null, hashLen);
/// <summary> /// Returns the current user's temporary path in combination with unique name /// starting with a given prefix, followed by a hash of the specified length. /// </summary> /// <param name="prefix"> /// This text is at the beginning of the name. /// <para> /// Uppercase letters are converted to lowercase letters. Supported /// characters are only from '0' to '9' and from 'a' to 'z' but can be /// completely empty to omit the prefix. /// </para> /// </param> /// <param name="hashLen"> /// The length of the hash. Valid values are 4 through 24. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// hashLen is not between 4 and 24. /// </exception> /// <exception cref="ArgumentInvalidException"> /// prefix contains invalid characters. /// </exception> public static string GetUniqueTempPath(string prefix = "tmp", int hashLen = 4) => PathEx.GetUniquePath("%TEMP%", prefix, null, hashLen);