Notes/Notes.Data/Models/Note.cs

73 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Utils;
namespace Notes.Models;
public class Note
{
public const string Extension = ".notes.txt";
public string Filename { get; set; }
public string Text { get; set; }
public DateTime Date { get; set; }
public string ShortName => Filename.Replace(Extension, string.Empty);
public static string AppDataDirectory
{
get
{
var appDataDirectory = FileSystem.Combine(AppContext.BaseDirectory, "Data");
IOUtils.EnsureDirectory(appDataDirectory,false);
return appDataDirectory;
}
}
public Note()
{
Filename = $"{FileSystem.GetRandomFileName()}{Extension}";
Date = DateTime.Now;
Text = "";
}
public void Save() =>
FileSystem.WriteAllText(FileSystem.Combine(AppDataDirectory, Filename), Text);
public void Delete() =>
FileSystem.Delete(FileSystem.Combine(AppDataDirectory, Filename));
public static Note Load(string filename)
{
filename = FileSystem.Combine(AppDataDirectory, filename);
if (!FileSystem.ExistsFile(filename))
throw new InvalidOperationException($"Unable to find file '{filename}' on local storage.");
return
new()
{
Filename = FileSystem.GetFileName(filename),
Text = FileSystem.ReadAllText(filename),
Date = FileSystem.GetLastWriteTime(filename)
};
}
public static IEnumerable<Note> LoadAll()
{
// Get the folder where the notes are stored.
string appDataPath = AppDataDirectory;
// Use Linq extensions to load the *.notes.txt files.
return FileSystem
// Select the file names from the directory
.EnumerateFiles(appDataPath, "*.notes.txt")
// Each file name is used to load a note
.Select(filename => Load(FileSystem.GetFileName(filename)))
// With the final collection of notes, order them by date
.OrderByDescending(note => note.Date);
}
}