Files
SabreTools/SabreTools.IO/Writers/IniWriter.cs

111 lines
2.7 KiB
C#
Raw Normal View History

2020-06-13 23:37:15 -07:00
using System;
using System.IO;
using System.Text;
2020-12-09 23:11:10 -08:00
namespace SabreTools.IO.Writers
2020-06-13 23:37:15 -07:00
{
public class IniWriter : IDisposable
{
/// <summary>
/// Internal stream writer for outputting
/// </summary>
2023-08-10 15:02:40 -04:00
private readonly StreamWriter? sw;
2020-06-13 23:37:15 -07:00
/// <summary>
/// Constructor for writing to a file
/// </summary>
public IniWriter(string filename)
{
sw = new StreamWriter(filename);
}
/// <summary>
/// Consturctor for writing to a stream
/// </summary>
public IniWriter(Stream stream, Encoding encoding)
{
sw = new StreamWriter(stream, encoding);
}
/// <summary>
/// Write a section tag
/// </summary>
2023-08-10 15:02:40 -04:00
public void WriteSection(string? value)
2020-06-13 23:37:15 -07:00
{
2023-08-10 15:02:40 -04:00
if (sw?.BaseStream == null)
return;
2020-06-13 23:37:15 -07:00
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("Section tag cannot be null or empty", nameof(value));
2020-06-13 23:37:15 -07:00
2020-06-14 13:05:28 -07:00
sw.WriteLine($"[{value.TrimStart('[').TrimEnd(']')}]");
2020-06-13 23:37:15 -07:00
}
/// <summary>
/// Write a key value pair
/// </summary>
2023-08-10 15:02:40 -04:00
public void WriteKeyValuePair(string key, string? value)
2020-06-13 23:37:15 -07:00
{
2023-08-10 15:02:40 -04:00
if (sw?.BaseStream == null)
return;
2020-06-13 23:37:15 -07:00
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("Key cannot be null or empty", nameof(key));
2020-06-13 23:37:15 -07:00
value ??= string.Empty;
2020-06-13 23:37:15 -07:00
sw.WriteLine($"{key}={value}");
}
/// <summary>
/// Write a comment
/// </summary>
2023-08-10 15:02:40 -04:00
public void WriteComment(string? value)
2020-06-13 23:37:15 -07:00
{
2023-08-10 15:02:40 -04:00
if (sw?.BaseStream == null)
return;
value ??= string.Empty;
2020-06-13 23:37:15 -07:00
sw.WriteLine($";{value}");
}
/// <summary>
/// Write a generic string
/// </summary>
2023-08-10 15:02:40 -04:00
public void WriteString(string? value)
2020-06-13 23:37:15 -07:00
{
2023-08-10 15:02:40 -04:00
if (sw?.BaseStream == null)
return;
value ??= string.Empty;
2020-06-13 23:37:15 -07:00
sw.Write(value);
}
/// <summary>
/// Write a newline
/// </summary>
public void WriteLine()
{
2023-08-10 15:02:40 -04:00
if (sw?.BaseStream == null)
return;
2020-06-13 23:37:15 -07:00
sw.WriteLine();
}
/// <summary>
/// Flush the underlying writer
/// </summary>
public void Flush()
{
2023-08-10 15:02:40 -04:00
sw?.Flush();
2020-06-13 23:37:15 -07:00
}
/// <summary>
/// Dispose of the underlying writer
/// </summary>
public void Dispose()
{
2023-08-10 15:02:40 -04:00
sw?.Dispose();
2020-06-13 23:37:15 -07:00
}
}
}