private static KeyValue LoadFromFile(string path, bool asBinary) { if (File.Exists(path) == false) { return(null); } try { using var input = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var kv = new KeyValue(); if (asBinary) { if (kv.ReadAsBinary(input) == false) { return(null); } } else { if (kv.ReadAsText(input) == false) { return(null); } } return(kv); } catch (Exception) { return(null); } }
/// <summary> /// Populate this instance from the given <see cref="Stream"/> as a binary <see cref="KeyValue"/>. /// </summary> /// <param name="input">The input <see cref="Stream"/> to read from.</param> /// <returns><c>true</c> if the read was successful; otherwise, <c>false</c>.</returns> public bool ReadAsBinary(Stream input) { this.Children = new List <KeyValue>(); while (true) { var type = (Type)input.ReadByte(); if (type == Type.End) { break; } var current = new KeyValue { Name = input.ReadNullTermString(Encoding.UTF8) }; try { switch (type) { case Type.None: { current.ReadAsBinary(input); break; } case Type.String: { current.Value = input.ReadNullTermString(Encoding.UTF8); break; } case Type.WideString: { throw new InvalidDataException("wstring is unsupported"); } case Type.Int32: case Type.Color: case Type.Pointer: { current.Value = Convert.ToString(input.ReadInt32()); break; } case Type.UInt64: { current.Value = Convert.ToString(input.ReadUInt64()); break; } case Type.Float32: { current.Value = Convert.ToString(input.ReadFloat(), CultureInfo.InvariantCulture); break; } default: { throw new InvalidDataException("Unknown KV type encountered."); } } } catch (InvalidDataException ex) { throw new InvalidDataException($"An exception ocurred while reading KV '{current.Name}'", ex); } this.Children.Add(current); } return(input.Position == input.Length); }