Skip to content

Instantly share code, notes, and snippets.

@jonas-johansson
Created February 15, 2023 17:14
Show Gist options
  • Save jonas-johansson/095e1cb8bb6fc1e093827e9c85904d1b to your computer and use it in GitHub Desktop.
Save jonas-johansson/095e1cb8bb6fc1e093827e9c85904d1b to your computer and use it in GitHub Desktop.
A collection of strings with a backing store on disk. It's useful if you want to have a persistent collection of strings in a pinch.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
/// <summary>
/// A collection of strings with a backing store on disk.
/// It's useful if you want to have a persistent collection of strings in a pinch.
/// </summary>
class FileBackedStringCollection : ICollection<string>
{
private List<string> backingList = new List<string>();
private string path;
public FileBackedStringList(string path)
{
this.path = path;
if (File.Exists(path))
{
File.ReadAllLines(path)
.ToList()
.ForEach(scene => Add(scene));
}
}
private void WriteToDisk()
{
File.WriteAllLines(path, this);
}
public IEnumerator<string> GetEnumerator()
{
return backingList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(string item)
{
backingList.Add(item);
WriteToDisk();
}
public void Clear()
{
backingList.Clear();
}
public bool Contains(string item)
{
return backingList.Contains(item);
}
public void CopyTo(string[] array, int arrayIndex)
{
backingList.CopyTo(array, arrayIndex);
}
public bool Remove(string item)
{
return backingList.Remove(item);
}
public int Count => backingList.Count;
public bool IsReadOnly => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment