using System.Collections; using System.Diagnostics; using System.Resources; using Brutal.Localization.ResX; namespace Brutal.Localization.ResX; /// /// A ResX reader to replace the defunct ResXResourceReader that no longer works in /// .NET Core. Supports only strings at present. /// public class ResXReader : IResourceReader { /// /// Create a ResXReader from a file path to a .resx file. /// /// Path to the file. Can be relative or absolute. public ResXReader(string filePath) { _data = []; _reader = new StreamReader(filePath); } /// /// Create a ResX reader that reads from a TextReader. /// /// public ResXReader(TextReader reader) { _data = []; _reader = reader; } /// /// Returns a read-only collection of the current resource data. /// public IReadOnlyDictionary Data { get { if (IsClosed) throw new InvalidOperationException("Reader is already closed"); EnsureLoaded(); return _data; } } #region System.Resources.IResourceReader /// /// Close the reader /// public void Close() { if (IsClosed) return; _reader!.Close(); _reader = null; } /// /// Return the IDictionaryEnumerator of the currently loaded data. /// /// The IDictionaryEnumerator of the currently loaded data. /// Thrown if the ResXReader is closed. public IDictionaryEnumerator GetEnumerator() { if (IsClosed) throw new InvalidOperationException("Reader is already closed"); EnsureLoaded(); return _data.GetEnumerator(); } /// /// Dispose of the ResXReader, closing the file in the process. /// public void Dispose() { Close(); GC.SuppressFinalize(this); } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { if (IsClosed) throw new InvalidOperationException("Reader is already closed"); return GetEnumerator(); } #endregion private void EnsureLoaded() { Debug.Assert(_reader is not null); Debug.Assert(!IsClosed); if (_loaded) return; _data = ResXFile.Parse(_reader.ReadToEnd()); _loaded = true; } private bool IsClosed => _reader is null; private bool _loaded; private Dictionary _data; private TextReader? _reader; }