16 Commits
1.1.0 ... 1.3.0

Author SHA1 Message Date
Matt Nadareski
75cc8376a8 Bump version 2023-11-21 11:24:19 -05:00
Matt Nadareski
0dea1fb437 Use Linq bridge library 2023-11-21 00:22:56 -05:00
Matt Nadareski
92df6b21e3 Support .NET Framework 2.0 2023-11-21 00:12:40 -05:00
Matt Nadareski
7da7967762 Support .NET Framework 3.5 2023-11-20 22:00:32 -05:00
Matt Nadareski
6c482ab98b Bump version 2023-11-14 13:46:34 -05:00
Matt Nadareski
8aaac551eb Cut off at .NET Framework 4.0 2023-11-08 10:47:42 -05:00
Matt Nadareski
026e2ee052 Move Linq-like methods 2023-11-08 01:37:27 -05:00
Matt Nadareski
9b3553e43f Support ancient .NET 2023-11-08 01:01:15 -05:00
Matt Nadareski
5221546af9 Expand supported RIDs 2023-11-07 23:31:59 -05:00
Matt Nadareski
658df0e91c Remove unnecessary csproj 2023-11-07 22:40:43 -05:00
Matt Nadareski
fd75f122d1 Enable latest language version 2023-11-07 22:04:05 -05:00
Matt Nadareski
886bc208dc Bump version 2023-09-08 14:03:58 -04:00
Matt Nadareski
5dc6290a87 Make byte array reading safer 2023-09-08 14:03:21 -04:00
Matt Nadareski
c8eb7d4d80 Add big-endian writing for byte arrays 2023-09-08 13:55:41 -04:00
Matt Nadareski
6035e2acaa Port byte array and stream extensions from BOS 2023-09-08 13:44:59 -04:00
Matt Nadareski
f51b19998f Add Nuget link to README 2023-09-08 12:04:10 -04:00
18 changed files with 639 additions and 447 deletions

View File

@@ -74,7 +74,7 @@ namespace SabreTools.IO
int i3 = BitConverter.ToInt32(retval, 8);
int i4 = BitConverter.ToInt32(retval, 12);
return new decimal(new int[] { i1, i2, i3, i4 });
return new decimal([i1, i2, i3, i4]);
}
/// <summary>

283
ByteArrayExtensions.cs Normal file
View File

@@ -0,0 +1,283 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace SabreTools.IO
{
/// <summary>
/// Extensions for byte arrays
/// </summary>
/// <remarks>TODO: Add U/Int24 and U/Int48 methods</remarks>
public static class ByteArrayExtensions
{
/// <summary>
/// Read a UInt8 and increment the pointer to an array
/// </summary>
public static byte ReadByte(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 1);
if (buffer == null)
return default;
return buffer[0];
}
/// <summary>
/// Read a UInt8[] and increment the pointer to an array
/// </summary>
public static byte[]? ReadBytes(this byte[]? content, ref int offset, int count)
{
// If the byte array is invalid, don't do anything
if (content == null)
return null;
// If there's an invalid byte count, don't do anything
if (count <= 0 || offset >= content.Length)
return null;
// Allocate enough space for the data requested
byte[] buffer = new byte[count];
// If we have less data left than requested, only read until the end
if (offset + count >= content.Length)
count = content.Length - offset;
// If we have a non-zero count, copy the data into the array
if (count > 0)
Array.Copy(content, offset, buffer, 0, Math.Min(count, content.Length - offset));
// Increment the offset and return
offset += count;
return buffer;
}
/// <summary>
/// Read a Int8 and increment the pointer to an array
/// </summary>
public static sbyte ReadSByte(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 1);
if (buffer == null)
return default;
return (sbyte)buffer[0];
}
/// <summary>
/// Read a Char and increment the pointer to an array
/// </summary>
public static char ReadChar(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 1);
if (buffer == null)
return default;
return (char)buffer[0];
}
/// <summary>
/// Read a Int16 and increment the pointer to an array
/// </summary>
public static short ReadInt16(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 2);
if (buffer == null)
return default;
return BitConverter.ToInt16(buffer, 0);
}
/// <summary>
/// Read a Int16 in big-endian format and increment the pointer to an array
/// </summary>
public static short ReadInt16BigEndian(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 2);
if (buffer == null)
return default;
Array.Reverse(buffer);
return BitConverter.ToInt16(buffer, 0);
}
/// <summary>
/// Read a UInt16 and increment the pointer to an array
/// </summary>
public static ushort ReadUInt16(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 2);
if (buffer == null)
return default;
return BitConverter.ToUInt16(buffer, 0);
}
/// <summary>
/// Read a UInt16 in big-endian format and increment the pointer to an array
/// </summary>
public static ushort ReadUInt16BigEndian(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 2);
if (buffer == null)
return default;
Array.Reverse(buffer);
return BitConverter.ToUInt16(buffer, 0);
}
/// <summary>
/// Read a Int32 and increment the pointer to an array
/// </summary>
public static int ReadInt32(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 4);
if (buffer == null)
return default;
return BitConverter.ToInt32(buffer, 0);
}
/// <summary>
/// Read a Int32 in big-endian format and increment the pointer to an array
/// </summary>
public static int ReadInt32BigEndian(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 4);
if (buffer == null)
return default;
Array.Reverse(buffer);
return BitConverter.ToInt32(buffer, 0);
}
/// <summary>
/// Read a UInt32 and increment the pointer to an array
/// </summary>
public static uint ReadUInt32(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 4);
if (buffer == null)
return default;
return BitConverter.ToUInt32(buffer, 0);
}
/// <summary>
/// Read a UInt32 in big-endian format and increment the pointer to an array
/// </summary>
public static uint ReadUInt32BigEndian(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 4);
if (buffer == null)
return default;
Array.Reverse(buffer);
return BitConverter.ToUInt32(buffer, 0);
}
/// <summary>
/// Read a Int64 and increment the pointer to an array
/// </summary>
public static long ReadInt64(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 8);
if (buffer == null)
return default;
return BitConverter.ToInt64(buffer, 0);
}
/// <summary>
/// Read a Int64 in big-endian format and increment the pointer to an array
/// </summary>
public static long ReadInt64BigEndian(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 8);
if (buffer == null)
return default;
Array.Reverse(buffer);
return BitConverter.ToInt64(buffer, 0);
}
/// <summary>
/// Read a UInt64 and increment the pointer to an array
/// </summary>
public static ulong ReadUInt64(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 8);
if (buffer == null)
return default;
return BitConverter.ToUInt64(buffer, 0);
}
/// <summary>
/// Read a UInt64 in big-endian format and increment the pointer to an array
/// </summary>
public static ulong ReadUInt64BigEndian(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 8);
if (buffer == null)
return default;
Array.Reverse(buffer);
return BitConverter.ToUInt64(buffer, 0);
}
/// <summary>
/// Read a Guid and increment the pointer to an array
/// </summary>
public static Guid ReadGuid(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 16);
if (buffer == null)
return default;
return new Guid(buffer);
}
/// <summary>
/// Read a Guid in big-endian format and increment the pointer to an array
/// </summary>
public static Guid ReadGuidBigEndian(this byte[] content, ref int offset)
{
byte[]? buffer = content.ReadBytes(ref offset, 16);
if (buffer == null)
return default;
Array.Reverse(buffer);
return new Guid(buffer);
}
/// <summary>
/// Read a null-terminated string from the stream
/// </summary>
public static string? ReadString(this byte[] content, ref int offset) => content.ReadString(ref offset, Encoding.Default);
/// <summary>
/// Read a null-terminated string from the stream
/// </summary>
public static string? ReadString(this byte[] content, ref int offset, Encoding encoding)
{
if (offset >= content.Length)
return null;
byte[] nullTerminator = encoding.GetBytes(new char[] { '\0' });
int charWidth = nullTerminator.Length;
var keyChars = new List<char>();
while (offset < content.Length)
{
char c = encoding.GetChars(content, offset, charWidth)[0];
keyChars.Add(c);
offset += charWidth;
if (c == '\0')
break;
}
return new string([.. keyChars]).TrimEnd('\0');
}
}
}

View File

@@ -19,7 +19,7 @@ namespace SabreTools.IO
public static string Ensure(this string dir, bool create = false)
{
// If the output directory is invalid
if (string.IsNullOrWhiteSpace(dir))
if (string.IsNullOrEmpty(dir))
dir = PathTool.GetRuntimeDirectory();
// Get the full path for the output directory
@@ -60,7 +60,7 @@ namespace SabreTools.IO
file.Dispose();
// Disable warning about UTF7 usage
#pragma warning disable SYSLIB0001
#pragma warning disable SYSLIB0001
// Analyze the BOM
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
@@ -70,7 +70,7 @@ namespace SabreTools.IO
if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;
return Encoding.Default;
#pragma warning restore SYSLIB0001
#pragma warning restore SYSLIB0001
}
catch
{
@@ -83,29 +83,21 @@ namespace SabreTools.IO
/// </summary>
/// <param name="path">Path to get extension from</param>
/// <returns>Extension, if possible</returns>
#if NET48
public static string GetNormalizedExtension(this string path)
#else
public static string? GetNormalizedExtension(this string? path)
#endif
{
// Check null or empty first
if (string.IsNullOrWhiteSpace(path))
if (string.IsNullOrEmpty(path))
return null;
// Get the extension from the path, if possible
#if NET48
string ext = Path.GetExtension(path)?.ToLowerInvariant();
#else
string? ext = Path.GetExtension(path)?.ToLowerInvariant();
#endif
// Check if the extension is null or empty
if (string.IsNullOrWhiteSpace(ext))
if (string.IsNullOrEmpty(ext))
return null;
// Make sure that extensions are valid
ext = ext.TrimStart('.');
ext = ext!.TrimStart('.');
return ext;
}
@@ -115,11 +107,7 @@ namespace SabreTools.IO
/// </summary>
/// <param name="root">Root directory to parse</param>
/// <returns>IEumerable containing all directories that are empty, an empty enumerable if the root is empty, null otherwise</returns>
#if NET48
public static List<string> ListEmpty(this string root)
#else
public static List<string>? ListEmpty(this string? root)
#endif
{
// Check null or empty first
if (string.IsNullOrEmpty(root))
@@ -130,13 +118,23 @@ namespace SabreTools.IO
return null;
// If it does and it is empty, return a blank enumerable
#if NET20 || NET35
if (!Directory.GetFiles(root, "*", SearchOption.AllDirectories).Any())
#else
if (!Directory.EnumerateFileSystemEntries(root, "*", SearchOption.AllDirectories).Any())
return new List<string>();
#endif
return [];
// Otherwise, get the complete list
#if NET20 || NET35
return Directory.GetDirectories(root, "*", SearchOption.AllDirectories)
.Where(dir => !Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Any())
.ToList();
#else
return Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories)
.Where(dir => !Directory.EnumerateFileSystemEntries(dir, "*", SearchOption.AllDirectories).Any())
.ToList();
#endif
}
}
}

View File

@@ -12,33 +12,15 @@ namespace SabreTools.IO
/// <summary>
/// Key-value pair INI file
/// </summary>
#if NET48
public class IniFile : IDictionary<string, string>
#else
public class IniFile : IDictionary<string, string?>
#endif
{
#if NET48
private Dictionary<string, string> _keyValuePairs = new Dictionary<string, string>();
#else
private Dictionary<string, string?>? _keyValuePairs = new Dictionary<string, string?>();
#endif
private Dictionary<string, string?>? _keyValuePairs = [];
#if NET48
public string this[string key]
#else
public string? this[string? key]
#endif
{
get
{
if (_keyValuePairs == null)
#if NET48
_keyValuePairs = new Dictionary<string, string>();
#else
_keyValuePairs = new Dictionary<string, string?>();
#endif
_keyValuePairs ??= [];
key = key?.ToLowerInvariant() ?? string.Empty;
if (_keyValuePairs.ContainsKey(key))
return _keyValuePairs[key];
@@ -47,13 +29,7 @@ namespace SabreTools.IO
}
set
{
if (_keyValuePairs == null)
#if NET48
_keyValuePairs = new Dictionary<string, string>();
#else
_keyValuePairs = new Dictionary<string, string?>();
#endif
_keyValuePairs ??= [];
key = key?.ToLowerInvariant() ?? string.Empty;
_keyValuePairs[key] = value;
}
@@ -113,20 +89,14 @@ namespace SabreTools.IO
if (!File.Exists(path))
return false;
using (var fileStream = File.OpenRead(path))
{
return Parse(fileStream);
}
using var fileStream = File.OpenRead(path);
return Parse(fileStream);
}
/// <summary>
/// Read an INI file from a stream
/// </summary>
#if NET48
public bool Parse(Stream stream)
#else
public bool Parse(Stream? stream)
#endif
{
// If the stream is invalid or unreadable, we can't process it
if (stream == null || !stream.CanRead || stream.Position >= stream.Length - 1)
@@ -135,46 +105,37 @@ namespace SabreTools.IO
// Keys are case-insensitive by default
try
{
using (var reader = new IniReader(stream, Encoding.UTF8))
// TODO: Can we use the section header in the reader?
using var reader = new IniReader(stream, Encoding.UTF8);
string? section = string.Empty;
while (!reader.EndOfStream)
{
// TODO: Can we use the section header in the reader?
#if NET48
string section = string.Empty;
#else
string? section = string.Empty;
#endif
while (!reader.EndOfStream)
// If we dont have a next line
if (!reader.ReadNextLine())
break;
// Process the row according to type
switch (reader.RowType)
{
// If we dont have a next line
if (!reader.ReadNextLine())
case IniRowType.SectionHeader:
section = reader.Section;
break;
// Process the row according to type
switch (reader.RowType)
{
case IniRowType.SectionHeader:
section = reader.Section;
break;
case IniRowType.KeyValue:
string? key = reader.KeyValuePair?.Key;
case IniRowType.KeyValue:
#if NET48
string key = reader.KeyValuePair?.Key;
#else
string? key = reader.KeyValuePair?.Key;
#endif
// Section names are prepended to the key with a '.' separating
if (!string.IsNullOrEmpty(section))
key = $"{section}.{key}";
// Section names are prepended to the key with a '.' separating
if (!string.IsNullOrEmpty(section))
key = $"{section}.{key}";
// Set or overwrite keys in the returned dictionary
this[key] = reader.KeyValuePair?.Value;
break;
// Set or overwrite keys in the returned dictionary
this[key] = reader.KeyValuePair?.Value;
break;
default:
// No-op
break;
}
default:
// No-op
break;
}
}
}
@@ -196,10 +157,8 @@ namespace SabreTools.IO
if (_keyValuePairs == null || _keyValuePairs.Count == 0)
return false;
using (var fileStream = File.OpenWrite(path))
{
return Write(fileStream);
}
using var fileStream = File.OpenWrite(path);
return Write(fileStream);
}
/// <summary>
@@ -217,43 +176,38 @@ namespace SabreTools.IO
try
{
using (IniWriter writer = new IniWriter(stream, Encoding.UTF8))
using IniWriter writer = new(stream, Encoding.UTF8);
// Order the dictionary by keys to link sections together
var orderedKeyValuePairs = _keyValuePairs.OrderBy(kvp => kvp.Key);
string section = string.Empty;
foreach (var keyValuePair in orderedKeyValuePairs)
{
// Order the dictionary by keys to link sections together
var orderedKeyValuePairs = _keyValuePairs.OrderBy(kvp => kvp.Key);
// Extract the key and value
string key = keyValuePair.Key;
string? value = keyValuePair.Value;
string section = string.Empty;
foreach (var keyValuePair in orderedKeyValuePairs)
// We assume '.' is a section name separator
if (key.Contains("."))
{
// Extract the key and value
string key = keyValuePair.Key;
#if NET48
string value = keyValuePair.Value;
#else
string? value = keyValuePair.Value;
#endif
// Split the key by '.'
string[] data = keyValuePair.Key.Split('.');
// We assume '.' is a section name separator
if (key.Contains('.'))
// If the key contains an '.', we need to put them back in
string newSection = data[0].Trim();
key = string.Join(".", data.Skip(1).ToArray()).Trim();
// If we have a new section, write it out
if (!string.Equals(newSection, section, StringComparison.OrdinalIgnoreCase))
{
// Split the key by '.'
string[] data = keyValuePair.Key.Split('.');
// If the key contains an '.', we need to put them back in
string newSection = data[0].Trim();
key = string.Join(".", data.Skip(1)).Trim();
// If we have a new section, write it out
if (!string.Equals(newSection, section, StringComparison.OrdinalIgnoreCase))
{
writer.WriteSection(newSection);
section = newSection;
}
writer.WriteSection(newSection);
section = newSection;
}
// Now write out the key and value in a standardized way
writer.WriteKeyValuePair(key, value);
}
// Now write out the key and value in a standardized way
writer.WriteKeyValuePair(key, value);
}
}
catch
@@ -267,61 +221,9 @@ namespace SabreTools.IO
#region IDictionary Impelementations
#if NET48
public ICollection<string> Keys => _keyValuePairs?.Keys;
public ICollection<string> Keys => _keyValuePairs?.Keys?.ToArray() ?? [];
public ICollection<string> Values => _keyValuePairs?.Values;
public int Count => _keyValuePairs?.Count ?? 0;
public bool IsReadOnly => false;
public void Add(string key, string value) => this[key] = value;
bool IDictionary<string, string>.Remove(string key) => Remove(key);
public bool TryGetValue(string key, out string value)
{
value = null;
return _keyValuePairs?.TryGetValue(key.ToLowerInvariant(), out value) ?? false;
}
public void Add(KeyValuePair<string, string> item) => this[item.Key] = item.Value;
public void Clear() => _keyValuePairs?.Clear();
public bool Contains(KeyValuePair<string, string> item)
{
var newItem = new KeyValuePair<string, string>(item.Key.ToLowerInvariant(), item.Value);
return (_keyValuePairs as ICollection<KeyValuePair<string, string>>)?.Contains(newItem) ?? false;
}
public bool ContainsKey(string key) => _keyValuePairs?.ContainsKey(key?.ToLowerInvariant() ?? string.Empty) ?? false;
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
{
(_keyValuePairs as ICollection<KeyValuePair<string, string>>)?.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<string, string> item)
{
var newItem = new KeyValuePair<string, string>(item.Key.ToLowerInvariant(), item.Value);
return (_keyValuePairs as ICollection<KeyValuePair<string, string>>)?.Remove(newItem) ?? false;
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return (_keyValuePairs as IEnumerable<KeyValuePair<string, string>>)?.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return (_keyValuePairs as IEnumerable)?.GetEnumerator();
}
#else
public ICollection<string> Keys => _keyValuePairs?.Keys?.ToArray() ?? Array.Empty<string>();
public ICollection<string?> Values => _keyValuePairs?.Values?.ToArray() ?? Array.Empty<string?>();
public ICollection<string?> Values => _keyValuePairs?.Values?.ToArray() ?? [];
public int Count => (_keyValuePairs as ICollection<KeyValuePair<string, string>>)?.Count ?? 0;
@@ -369,7 +271,6 @@ namespace SabreTools.IO
{
return (_keyValuePairs as IEnumerable)!.GetEnumerator();
}
#endif
#endregion
}

View File

@@ -23,7 +23,7 @@ namespace NaturalSort
public NaturalComparer()
{
table = new Dictionary<string, string[]>();
table = [];
}
public void Dispose()
@@ -31,11 +31,7 @@ namespace NaturalSort
table.Clear();
}
#if NET48
public override int Compare(string x, string y)
#else
public override int Compare(string? x, string? y)
#endif
{
if (x == null || y == null)
{
@@ -50,24 +46,16 @@ namespace NaturalSort
{
return x.CompareTo(y);
}
#if NET48
if (!table.TryGetValue(x, out string[] x1))
#else
if (!table.TryGetValue(x, out string[]? x1))
#endif
{
//x1 = Regex.Split(x.Replace(" ", string.Empty), "([0-9]+)");
x1 = Regex.Split(x.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
x1 = Regex.Split(x.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(x, x1);
}
#if NET48
if (!table.TryGetValue(y, out string[] y1))
#else
if (!table.TryGetValue(y, out string[]? y1))
#endif
{
//y1 = Regex.Split(y.Replace(" ", string.Empty), "([0-9]+)");
y1 = Regex.Split(y.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
y1 = Regex.Split(y.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(y, y1);
}

View File

@@ -23,7 +23,7 @@ namespace NaturalSort
public NaturalReversedComparer()
{
table = new Dictionary<string, string[]>();
table = [];
}
public void Dispose()
@@ -31,11 +31,7 @@ namespace NaturalSort
table.Clear();
}
#if NET48
public override int Compare(string x, string y)
#else
public override int Compare(string? x, string? y)
#endif
{
if (x == null || y == null)
{
@@ -50,24 +46,16 @@ namespace NaturalSort
{
return y.CompareTo(x);
}
#if NET48
if (!table.TryGetValue(x, out string[] x1))
#else
if (!table.TryGetValue(x, out string[]? x1))
#endif
{
//x1 = Regex.Split(x.Replace(" ", string.Empty), "([0-9]+)");
x1 = Regex.Split(x.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
x1 = Regex.Split(x.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(x, x1);
}
#if NET48
if (!table.TryGetValue(y, out string[] y1))
#else
if (!table.TryGetValue(y, out string[]? y1))
#endif
{
//y1 = Regex.Split(y.Replace(" ", string.Empty), "([0-9]+)");
y1 = Regex.Split(y.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
y1 = Regex.Split(y.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(y, y1);
}

View File

@@ -1,8 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -11,26 +11,14 @@ namespace SabreTools.IO
/// <summary>
/// Current full path represented
/// </summary>
#if NET48
public string CurrentPath { get; private set; }
#else
public string CurrentPath { get; init; }
#endif
/// <summary>
/// Possible parent path represented (may be null or empty)
/// </summary>
#if NET48
public string ParentPath { get; private set; }
#else
public string? ParentPath { get; init; }
#endif
public string? ParentPath { get; private set; }
#if NET48
public ParentablePath(string currentPath, string parentPath = null)
#else
public ParentablePath(string currentPath, string? parentPath = null)
#endif
{
CurrentPath = currentPath;
ParentPath = parentPath;
@@ -41,22 +29,18 @@ namespace SabreTools.IO
/// </summary>
/// <param name="sanitize">True if path separators should be converted to '-', false otherwise</param>
/// <returns>Subpath for the file</returns>
#if NET48
public string GetNormalizedFileName(bool sanitize)
#else
public string? GetNormalizedFileName(bool sanitize)
#endif
{
// If the current path is empty, we can't do anything
if (string.IsNullOrWhiteSpace(CurrentPath))
if (string.IsNullOrEmpty(CurrentPath))
return null;
// Assume the current path is the filename
string filename = Path.GetFileName(CurrentPath);
// If we have a true ParentPath, remove it from CurrentPath and return the remainder
if (!string.IsNullOrWhiteSpace(ParentPath) && !string.Equals(CurrentPath, ParentPath, StringComparison.Ordinal))
filename = CurrentPath.Remove(0, ParentPath.Length + 1);
if (string.IsNullOrEmpty(ParentPath) && !string.Equals(CurrentPath, ParentPath, StringComparison.Ordinal))
filename = CurrentPath.Remove(0, ParentPath!.Length + 1);
// If we're sanitizing the path after, do so
if (sanitize)
@@ -71,22 +55,18 @@ namespace SabreTools.IO
/// <param name="outDir">Output directory to use</param>
/// <param name="inplace">True if the output file should go to the same input folder, false otherwise</param>
/// <returns>Complete output path</returns>
#if NET48
public string GetOutputPath(string outDir, bool inplace)
#else
public string? GetOutputPath(string outDir, bool inplace)
#endif
{
// If the current path is empty, we can't do anything
if (string.IsNullOrWhiteSpace(CurrentPath))
if (string.IsNullOrEmpty(CurrentPath))
return null;
// If the output dir is empty (and we're not inplace), we can't do anything
if (string.IsNullOrWhiteSpace(outDir) && !inplace)
if (string.IsNullOrEmpty(outDir) && !inplace)
return null;
// Check if we have a split path or not
bool splitpath = !string.IsNullOrWhiteSpace(ParentPath);
bool splitpath = !string.IsNullOrEmpty(ParentPath);
// If we have an inplace output, use the directory name from the input path
if (inplace)
@@ -105,15 +85,9 @@ namespace SabreTools.IO
workingParent = Path.GetDirectoryName(ParentPath ?? string.Empty) ?? string.Empty;
// Determine the correct subfolder based on the working parent directory
#if NET48
int extraLength = workingParent.EndsWith(":")
|| workingParent.EndsWith(Path.DirectorySeparatorChar.ToString())
|| workingParent.EndsWith(Path.AltDirectorySeparatorChar.ToString()) ? 0 : 1;
#else
int extraLength = workingParent.EndsWith(':')
|| workingParent.EndsWith(Path.DirectorySeparatorChar)
|| workingParent.EndsWith(Path.AltDirectorySeparatorChar) ? 0 : 1;
#endif
return Path.GetDirectoryName(Path.Combine(outDir, CurrentPath.Remove(0, workingParent.Length + extraLength)));
}

View File

@@ -29,14 +29,10 @@ namespace SabreTools.IO
// If we have a wildcard
string pattern = "*";
if (input.Contains('*') || input.Contains('?'))
if (input.Contains("*") || input.Contains("?"))
{
pattern = Path.GetFileName(input);
#if NET48
input = input.Substring(0, input.Length - pattern.Length);
#else
input = input[..^pattern.Length];
#endif
}
// Get the parent path in case of appending
@@ -62,7 +58,7 @@ namespace SabreTools.IO
/// <returns>List with all new files</returns>
private static List<string> GetDirectoriesOrdered(string dir, string pattern = "*")
{
return GetDirectoriesOrderedHelper(dir, new List<string>(), pattern);
return GetDirectoriesOrderedHelper(dir, [], pattern);
}
/// <summary>
@@ -75,7 +71,7 @@ namespace SabreTools.IO
private static List<string> GetDirectoriesOrderedHelper(string dir, List<string> infiles, string pattern)
{
// Take care of the files in the top directory
List<string> toadd = Directory.EnumerateDirectories(dir, pattern, SearchOption.TopDirectoryOnly).ToList();
List<string> toadd = [.. Directory.GetDirectories(dir, pattern, SearchOption.TopDirectoryOnly)];
toadd.Sort(new NaturalComparer());
infiles.AddRange(toadd);
@@ -108,14 +104,10 @@ namespace SabreTools.IO
// If we have a wildcard
string pattern = "*";
if (input.Contains('*') || input.Contains('?'))
if (input.Contains("*") || input.Contains("?"))
{
pattern = Path.GetFileName(input);
#if NET48
input = input.Substring(0, input.Length - pattern.Length);
#else
input = input[..^pattern.Length];
#endif
}
// Get the parent path in case of appending
@@ -145,7 +137,7 @@ namespace SabreTools.IO
/// <returns>List with all new files</returns>
public static List<string> GetFilesOrdered(string dir, string pattern = "*")
{
return GetFilesOrderedHelper(dir, new List<string>(), pattern);
return GetFilesOrderedHelper(dir, [], pattern);
}
/// <summary>
@@ -158,12 +150,12 @@ namespace SabreTools.IO
private static List<string> GetFilesOrderedHelper(string dir, List<string> infiles, string pattern)
{
// Take care of the files in the top directory
List<string> toadd = Directory.EnumerateFiles(dir, pattern, SearchOption.TopDirectoryOnly).ToList();
List<string> toadd = [.. Directory.GetFiles(dir, pattern, SearchOption.TopDirectoryOnly)];
toadd.Sort(new NaturalComparer());
infiles.AddRange(toadd);
// Then recurse through and add from the directories
List<string> subDirs = Directory.EnumerateDirectories(dir, pattern, SearchOption.TopDirectoryOnly).ToList();
List<string> subDirs = [.. Directory.GetDirectories(dir, pattern, SearchOption.TopDirectoryOnly)];
subDirs.Sort(new NaturalComparer());
foreach (string subdir in subDirs)
{
@@ -173,7 +165,7 @@ namespace SabreTools.IO
// Return the new list
return infiles;
}
/// <summary>
/// Get the current runtime directory
/// </summary>

View File

@@ -7,3 +7,5 @@ This library comprises I/O functionality for the following file types:
- Separated-Value files (e.g. CSV, SSV, TSV)
There are also some extensions that are useful for wrapping common functionality required by SabreTools.
Find the link to the Nuget package [here](https://www.nuget.org/packages/SabreTools.IO).

View File

@@ -23,20 +23,12 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Internal stream reader for inputting
/// </summary>
#if NET48
private readonly StreamReader sr;
#else
private readonly StreamReader? sr;
#endif
/// <summary>
/// Contents of the current line, unprocessed
/// </summary>
#if NET48
public string CurrentLine { get; private set; } = string.Empty;
#else
public string? CurrentLine { get; private set; } = string.Empty;
#endif
/// <summary>
/// Get the current line number
@@ -57,20 +49,12 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Contents of the currently read line as an internal item
/// </summary>
#if NET48
public Dictionary<string, string> Internal { get; private set; } = new Dictionary<string, string>();
#else
public Dictionary<string, string>? Internal { get; private set; } = new Dictionary<string, string>();
#endif
public Dictionary<string, string>? Internal { get; private set; } = [];
/// <summary>
/// Current internal item name
/// </summary>
#if NET48
public string InternalName { get; private set; }
#else
public string? InternalName { get; private set; }
#endif
/// <summary>
/// Get if we should be making DosCenter exceptions
@@ -101,11 +85,7 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Current top-level being read
/// </summary>
#if NET48
public string TopLevel { get; private set; } = string.Empty;
#else
public string? TopLevel { get; private set; } = string.Empty;
#endif
/// <summary>
/// Constructor for opening a write from a file
@@ -151,11 +131,7 @@ namespace SabreTools.IO.Readers
// Standalone (special case for DC dats)
if (CurrentLine.StartsWith("Name:"))
{
#if NET48
string temp = CurrentLine.Substring("Name:".Length).Trim();
#else
string temp = CurrentLine["Name:".Length..].Trim();
#endif
CurrentLine = $"Name: {temp}";
}
@@ -188,11 +164,11 @@ namespace SabreTools.IO.Readers
string normalizedValue = gc[1].Value.ToLowerInvariant();
string[] linegc = SplitLineAsCMP(gc[2].Value);
Internal = new Dictionary<string, string>();
Internal = [];
for (int i = 0; i < linegc.Length; i++)
{
string key = linegc[i].Replace("\"", string.Empty);
if (string.IsNullOrWhiteSpace(key))
if (string.IsNullOrEmpty(key))
continue;
string value = string.Empty;

View File

@@ -11,11 +11,7 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Internal stream reader for inputting
/// </summary>
#if NET48
private readonly StreamReader sr;
#else
private readonly StreamReader? sr;
#endif
/// <summary>
/// Get if at end of stream
@@ -36,11 +32,7 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Contents of the current line, unprocessed
/// </summary>
#if NET48
public string CurrentLine { get; private set; } = string.Empty;
#else
public string? CurrentLine { get; private set; } = string.Empty;
#endif
/// <summary>
/// Get the current line number
@@ -55,11 +47,7 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Current section being read
/// </summary>
#if NET48
public string Section { get; private set; } = string.Empty;
#else
public string? Section { get; private set; } = string.Empty;
#endif
/// <summary>
/// Validate that rows are in key=value format
@@ -123,14 +111,14 @@ namespace SabreTools.IO.Readers
}
// KeyValuePair
else if (CurrentLine.Contains('='))
else if (CurrentLine.Contains("="))
{
// Split the line by '=' for key-value pairs
string[] data = CurrentLine.Split('=');
// If the value field contains an '=', we need to put them back in
string key = data[0].Trim();
string value = string.Join("=", data.Skip(1)).Trim();
string value = string.Join("=", data.Skip(1).ToArray()).Trim();
KeyValuePair = new KeyValuePair<string, string>(key, value);
RowType = IniRowType.KeyValue;

View File

@@ -12,11 +12,7 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Internal stream reader for inputting
/// </summary>
#if NET48
private readonly StreamReader sr;
#else
private readonly StreamReader? sr;
#endif
/// <summary>
/// Internal value to say how many fields should be written
@@ -37,11 +33,7 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Contents of the current line, unprocessed
/// </summary>
#if NET48
public string CurrentLine { get; private set; } = string.Empty;
#else
public string? CurrentLine { get; private set; } = string.Empty;
#endif
/// <summary>
/// Get the current line number
@@ -56,20 +48,12 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Header row values
/// </summary>
#if NET48
public List<string> HeaderValues { get; set; } = null;
#else
public List<string>? HeaderValues { get; set; } = null;
#endif
/// <summary>
/// Get the current line values
/// </summary>
#if NET48
public List<string> Line { get; private set; } = null;
#else
public List<string>? Line { get; private set; } = null;
#endif
/// <summary>
/// Assume that values are wrapped in quotes
@@ -127,11 +111,7 @@ namespace SabreTools.IO.Readers
if (!sr.BaseStream.CanRead || sr.EndOfStream)
return false;
#if NET48
string fullLine = sr.ReadLine();
#else
string? fullLine = sr.ReadLine();
#endif
CurrentLine = fullLine;
LineNumber++;
@@ -144,9 +124,11 @@ namespace SabreTools.IO.Readers
// https://stackoverflow.com/questions/3776458/split-a-comma-separated-string-with-both-quoted-and-unquoted-strings
var lineSplitRegex = new Regex($"(?:^|{Separator})(\"(?:[^\"]+|\"\")*\"|[^{Separator}]*)");
var temp = new List<string>();
foreach (Match match in lineSplitRegex.Matches(fullLine))
foreach (Match? match in lineSplitRegex.Matches(fullLine).Cast<Match?>())
{
string curr = match.Value;
string? curr = match?.Value;
if (curr == null)
continue;
if (curr.Length == 0)
temp.Add("");
@@ -157,7 +139,7 @@ namespace SabreTools.IO.Readers
Line = temp;
}
// Otherwise, just split on the delimiter
else
{
@@ -181,11 +163,7 @@ namespace SabreTools.IO.Readers
/// <summary>
/// Get the value for the current line for the current key
/// </summary>
#if NET48
public string GetValue(string key)
#else
public string? GetValue(string key)
#endif
{
// No header means no key-based indexing
if (!Header)

View File

@@ -2,9 +2,12 @@
<PropertyGroup>
<!-- Assembly Properties -->
<TargetFrameworks>net48;net6.0;net7.0;net8.0</TargetFrameworks>
<RuntimeIdentifiers>win-x86;win-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<Version>1.1.0</Version>
<TargetFrameworks>net20;net35;net40;net452;net462;net472;net48;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>1.3.0</Version>
<!-- Package Properties -->
<Authors>Matt Nadareski</Authors>
@@ -18,12 +21,13 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'!='net48'">
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath=""/>
</ItemGroup>
<!-- Support for old .NET versions -->
<ItemGroup Condition="$(TargetFramework.StartsWith(`net2`)) OR $(TargetFramework.StartsWith(`net3`))">
<PackageReference Include="Net30.LinqBridge" Version="1.3.0" />
</ItemGroup>
</Project>

View File

@@ -1,12 +1,235 @@
using System.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SabreTools.IO
{
/// <summary>
/// Extensions to Stream functionality
/// Extensions for Streams
/// </summary>
/// <remarks>TODO: Add U/Int24 and U/Int48 methods</remarks>
public static class StreamExtensions
{
/// <summary>
/// Read a UInt8 from the stream
/// </summary>
public static byte ReadByteValue(this Stream stream)
{
byte[] buffer = new byte[1];
stream.Read(buffer, 0, 1);
return buffer[0];
}
/// <summary>
/// Read a UInt8[] from the stream
/// </summary>
public static byte[]? ReadBytes(this Stream stream, int count)
{
// If there's an invalid byte count, don't do anything
if (count <= 0)
return null;
byte[] buffer = new byte[count];
stream.Read(buffer, 0, count);
return buffer;
}
/// <summary>
/// Read a Int8 from the stream
/// </summary>
public static sbyte ReadSByte(this Stream stream)
{
byte[] buffer = new byte[1];
stream.Read(buffer, 0, 1);
return (sbyte)buffer[0];
}
/// <summary>
/// Read a Char from the stream
/// </summary>
public static char ReadChar(this Stream stream)
{
byte[] buffer = new byte[1];
stream.Read(buffer, 0, 1);
return (char)buffer[0];
}
/// <summary>
/// Read a Int16 from the stream
/// </summary>
public static short ReadInt16(this Stream stream)
{
byte[] buffer = new byte[2];
stream.Read(buffer, 0, 2);
return BitConverter.ToInt16(buffer, 0);
}
/// <summary>
/// Read a Int16 from the stream in big-endian format
/// </summary>
public static short ReadInt16BigEndian(this Stream stream)
{
byte[] buffer = new byte[2];
stream.Read(buffer, 0, 2);
Array.Reverse(buffer);
return BitConverter.ToInt16(buffer, 0);
}
/// <summary>
/// Read a UInt16 from the stream
/// </summary>
public static ushort ReadUInt16(this Stream stream)
{
byte[] buffer = new byte[2];
stream.Read(buffer, 0, 2);
return BitConverter.ToUInt16(buffer, 0);
}
/// <summary>
/// Read a UInt16 from the stream in big-endian format
/// </summary>
public static ushort ReadUInt16BigEndian(this Stream stream)
{
byte[] buffer = new byte[2];
stream.Read(buffer, 0, 2);
Array.Reverse(buffer);
return BitConverter.ToUInt16(buffer, 0);
}
/// <summary>
/// Read an Int32 from the stream
/// </summary>
public static int ReadInt32(this Stream stream)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);
}
/// <summary>
/// Read an Int32 from the stream in big-endian format
/// </summary>
public static int ReadInt32BigEndian(this Stream stream)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
Array.Reverse(buffer);
return BitConverter.ToInt32(buffer, 0);
}
/// <summary>
/// Read a UInt32 from the stream
/// </summary>
public static uint ReadUInt32(this Stream stream)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
return BitConverter.ToUInt32(buffer, 0);
}
/// <summary>
/// Read a UInt32 from the stream in big-endian format
/// </summary>
public static uint ReadUInt32BigEndian(this Stream stream)
{
byte[] buffer = new byte[4];
stream.Read(buffer, 0, 4);
Array.Reverse(buffer);
return BitConverter.ToUInt32(buffer, 0);
}
/// <summary>
/// Read a Int64 from the stream
/// </summary>
public static long ReadInt64(this Stream stream)
{
byte[] buffer = new byte[8];
stream.Read(buffer, 0, 8);
return BitConverter.ToInt64(buffer, 0);
}
/// <summary>
/// Read a Int64 from the stream in big-endian format
/// </summary>
public static long ReadInt64BigEndian(this Stream stream)
{
byte[] buffer = new byte[8];
stream.Read(buffer, 0, 8);
Array.Reverse(buffer);
return BitConverter.ToInt64(buffer, 0);
}
/// <summary>
/// Read a UInt64 from the stream
/// </summary>
public static ulong ReadUInt64(this Stream stream)
{
byte[] buffer = new byte[8];
stream.Read(buffer, 0, 8);
return BitConverter.ToUInt64(buffer, 0);
}
/// <summary>
/// Read a UInt64 from the stream in big-endian format
/// </summary>
public static ulong ReadUInt64BigEndian(this Stream stream)
{
byte[] buffer = new byte[8];
stream.Read(buffer, 0, 8);
Array.Reverse(buffer);
return BitConverter.ToUInt64(buffer, 0);
}
/// <summary>
/// Read a Guid from the stream
/// </summary>
public static Guid ReadGuid(this Stream stream)
{
byte[] buffer = new byte[16];
stream.Read(buffer, 0, 16);
return new Guid(buffer);
}
/// <summary>
/// Read a Guid from the stream in big-endian format
/// </summary>
public static Guid ReadGuidBigEndian(this Stream stream)
{
byte[] buffer = new byte[16];
stream.Read(buffer, 0, 16);
Array.Reverse(buffer);
return new Guid(buffer);
}
/// <summary>
/// Read a null-terminated string from the stream
/// </summary>
public static string? ReadString(this Stream stream) => stream.ReadString(Encoding.Default);
/// <summary>
/// Read a null-terminated string from the stream
/// </summary>
public static string? ReadString(this Stream stream, Encoding encoding)
{
if (stream.Position >= stream.Length)
return null;
byte[] nullTerminator = encoding.GetBytes(new char[] { '\0' });
int charWidth = nullTerminator.Length;
var tempBuffer = new List<byte>();
byte[] buffer = new byte[charWidth];
while (stream.Position < stream.Length && stream.Read(buffer, 0, charWidth) != 0 && !buffer.SequenceEqual(nullTerminator))
{
tempBuffer.AddRange(buffer);
}
return encoding.GetString([.. tempBuffer]);
}
/// <summary>
/// Seek to a specific point in the stream, if possible
/// </summary>

View File

@@ -44,20 +44,6 @@ namespace SabreTools.IO.Writers
/// <summary>
/// Tag information for the stack
/// </summary>
#if NET48
private class TagInfo
{
public string Name { get; set; }
public bool Mixed { get; set; }
public void Init()
{
Name = null;
Mixed = false;
}
}
#else
private record struct TagInfo(string? Name, bool Mixed)
{
public void Init()
@@ -66,7 +52,6 @@ namespace SabreTools.IO.Writers
Mixed = false;
}
}
#endif
/// <summary>
/// Internal stream writer
@@ -86,7 +71,7 @@ namespace SabreTools.IO.Writers
/// <summary>
/// State table for determining the state machine
/// </summary>
private readonly State[] stateTable = {
private readonly State[] stateTable = [
// State.Start State.Prolog State.Element State.Attribute State.Content State.AttrOnly State.Epilog
//
/* Token.None */ State.Prolog, State.Prolog, State.Content, State.Content, State.Content, State.Error, State.Epilog,
@@ -97,7 +82,7 @@ namespace SabreTools.IO.Writers
/* Token.StartAttribute */ State.AttrOnly, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error,
/* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Element, State.Error, State.Epilog, State.Error,
/* Token.Content */ State.Content, State.Content, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
};
];
/// <summary>
/// Current state in the machine
@@ -185,11 +170,7 @@ namespace SabreTools.IO.Writers
/// <summary>
/// Write a complete element with content
/// </summary>
#if NET48
public void WriteElementString(string name, string value)
#else
public void WriteElementString(string name, string? value)
#endif
{
WriteStartElement(name);
WriteString(value);
@@ -202,11 +183,7 @@ namespace SabreTools.IO.Writers
/// <param name="name">Name of the element</param>
/// <param name="value">Value to write in the element</param>
/// <param name="throwOnError">Indicates if an error should be thrown on a missing required value</param>
#if NET48
public void WriteRequiredElementString(string name, string value, bool throwOnError = false)
#else
public void WriteRequiredElementString(string name, string? value, bool throwOnError = false)
#endif
{
// Throw an exception if we are configured to
if (value == null && throwOnError)
@@ -220,11 +197,7 @@ namespace SabreTools.IO.Writers
/// </summary>
/// <param name="name">Name of the element</param>
/// <param name="value">Value to write in the element</param>
#if NET48
public void WriteOptionalElementString(string name, string value)
#else
public void WriteOptionalElementString(string name, string? value)
#endif
{
if (!string.IsNullOrEmpty(value))
WriteElementString(name, value);
@@ -277,11 +250,7 @@ namespace SabreTools.IO.Writers
/// <param name="name">Name of the attribute</param>
/// <param name="value">Value to write in the attribute</param>
/// <param name="quoteOverride">Non-null to overwrite the writer setting, null otherwise</param>
#if NET48
public void WriteAttributeString(string name, string value, bool? quoteOverride = null)
#else
public void WriteAttributeString(string name, string? value, bool? quoteOverride = null)
#endif
{
WriteStartAttribute(name, quoteOverride);
WriteString(value);
@@ -295,11 +264,7 @@ namespace SabreTools.IO.Writers
/// <param name="value">Value to write in the attribute</param>
/// <param name="quoteOverride">Non-null to overwrite the writer setting, null otherwise</param>
/// <param name="throwOnError">Indicates if an error should be thrown on a missing required value</param>
#if NET48
public void WriteRequiredAttributeString(string name, string value, bool? quoteOverride = null, bool throwOnError = false)
#else
public void WriteRequiredAttributeString(string name, string? value, bool? quoteOverride = null, bool throwOnError = false)
#endif
{
// Throw an exception if we are configured to
if (value == null && throwOnError)
@@ -314,11 +279,7 @@ namespace SabreTools.IO.Writers
/// <param name="name">Name of the attribute</param>
/// <param name="value">Value to write in the attribute</param>
/// <param name="quoteOverride">Non-null to overwrite the writer setting, null otherwise</param>
#if NET48
public void WriteOptionalAttributeString(string name, string value, bool? quoteOverride = null)
#else
public void WriteOptionalAttributeString(string name, string? value, bool? quoteOverride = null)
#endif
{
if (!string.IsNullOrEmpty(value))
WriteAttributeString(name, value, quoteOverride);
@@ -330,11 +291,7 @@ namespace SabreTools.IO.Writers
/// <param name="name">Name of the attribute</param>
/// <param name="value">Value to write in the attribute</param>
/// <param name="quoteOverride">Non-null to overwrite the writer setting, null otherwise</param>
#if NET48
public void WriteStandalone(string name, string value, bool? quoteOverride = null)
#else
public void WriteStandalone(string name, string? value, bool? quoteOverride = null)
#endif
{
try
{
@@ -378,11 +335,7 @@ namespace SabreTools.IO.Writers
/// <param name="value">Value to write in the attribute</param>
/// <param name="quoteOverride">Non-null to overwrite the writer setting, null otherwise</param>
/// <param name="throwOnError">Indicates if an error should be thrown on a missing required value</param>
#if NET48
public void WriteRequiredStandalone(string name, string value, bool? quoteOverride = null, bool throwOnError = false)
#else
public void WriteRequiredStandalone(string name, string? value, bool? quoteOverride = null, bool throwOnError = false)
#endif
{
// Throw an exception if we are configured to
if (value == null && throwOnError)
@@ -397,11 +350,7 @@ namespace SabreTools.IO.Writers
/// <param name="name">Name of the attribute</param>
/// <param name="value">Value to write in the attribute</param>
/// <param name="quoteOverride">Non-null to overwrite the writer setting, null otherwise</param>
#if NET48
public void WriteOptionalStandalone(string name, string value, bool? quoteOverride = null)
#else
public void WriteOptionalStandalone(string name, string? value, bool? quoteOverride = null)
#endif
{
if (!string.IsNullOrEmpty(value))
WriteStandalone(name, value, quoteOverride);
@@ -410,11 +359,7 @@ namespace SabreTools.IO.Writers
/// <summary>
/// Write a string content value
/// </summary>
#if NET48
public void WriteString(string value)
#else
public void WriteString(string? value)
#endif
{
try
{
@@ -424,7 +369,7 @@ namespace SabreTools.IO.Writers
// If we're writing quotes, don't write out quote characters internally
if (Quotes)
value = value.Replace("\"", "''");
value = value!.Replace("\"", "''");
sw.Write(value);
}

View File

@@ -9,11 +9,7 @@ namespace SabreTools.IO.Writers
/// <summary>
/// Internal stream writer for outputting
/// </summary>
#if NET48
private readonly StreamWriter sw;
#else
private readonly StreamWriter? sw;
#endif
/// <summary>
/// Constructor for writing to a file
@@ -34,81 +30,53 @@ namespace SabreTools.IO.Writers
/// <summary>
/// Write a section tag
/// </summary>
#if NET48
public void WriteSection(string value)
#else
public void WriteSection(string? value)
#endif
{
if (sw?.BaseStream == null)
return;
if (string.IsNullOrWhiteSpace(value))
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Section tag cannot be null or empty", nameof(value));
sw.WriteLine($"[{value.TrimStart('[').TrimEnd(']')}]");
sw.WriteLine($"[{value!.TrimStart('[').TrimEnd(']')}]");
}
/// <summary>
/// Write a key value pair
/// </summary>
#if NET48
public void WriteKeyValuePair(string key, string value)
#else
public void WriteKeyValuePair(string key, string? value)
#endif
{
if (sw?.BaseStream == null)
return;
if (string.IsNullOrWhiteSpace(key))
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key cannot be null or empty", nameof(key));
#if NET48
value = value != null ? value : string.Empty;
#else
value ??= string.Empty;
#endif
sw.WriteLine($"{key}={value}");
}
/// <summary>
/// Write a comment
/// </summary>
#if NET48
public void WriteComment(string value)
#else
public void WriteComment(string? value)
#endif
{
if (sw?.BaseStream == null)
return;
#if NET48
value = value != null ? value : string.Empty;
#else
value ??= string.Empty;
#endif
sw.WriteLine($";{value}");
}
/// <summary>
/// Write a generic string
/// </summary>
#if NET48
public void WriteString(string value)
#else
public void WriteString(string? value)
#endif
{
if (sw?.BaseStream == null)
return;
#if NET48
value = value != null ? value : string.Empty;
#else
value ??= string.Empty;
#endif
sw.Write(value);
}
@@ -119,7 +87,7 @@ namespace SabreTools.IO.Writers
{
if (sw?.BaseStream == null)
return;
sw.WriteLine();
}

View File

@@ -60,11 +60,7 @@ namespace SabreTools.IO.Writers
/// <summary>
/// Write a header row
/// </summary>
#if NET48
public void WriteHeader(string[] headers)
#else
public void WriteHeader(string?[] headers)
#endif
{
// If we haven't written anything out, we can write headers
if (!header && !firstRow)
@@ -76,11 +72,7 @@ namespace SabreTools.IO.Writers
/// <summary>
/// Write a value row
/// </summary>
#if NET48
public void WriteValues(object[] values, bool newline = true)
#else
public void WriteValues(object?[] values, bool newline = true)
#endif
{
// If the writer can't be used, we error
if (sw == null || !sw.BaseStream.CanWrite)