Notes/Services/FileNoteService.cs
2023-05-12 12:38:13 -04:00

56 lines
1.6 KiB
C#

namespace BinaryDad.Notes.Services
{
public class FileNoteService : INoteService
{
private readonly string? defaultFileName;
private readonly string? filePath;
public FileNoteService(IConfiguration configuration)
{
defaultFileName = configuration["DefaultContentFileName"].Trim().ToLower();
filePath = configuration["ContentFilePath"].Trim();
CheckFile(defaultFileName);
}
public string GetText(string? noteName)
{
CheckFile(noteName);
return File.ReadAllText(GetFilePath(noteName));
}
public ICollection<string> GetNoteNames()
{
return Directory.GetFiles(filePath)
.Select(f => Path.GetFileName(f))
.ToList();
}
public void SaveText(string content, string? noteName)
{
File.WriteAllText(GetFilePath(noteName), content);
}
private void CheckFile(string noteName)
{
var filePath = GetFilePath(noteName);
// ensure initialized
if (!File.Exists(filePath))
{
SaveText("Hi! Feel free to start typing. Everything will be saved soon after you are done typing.", noteName);
}
}
private string GetFilePath(string? noteName)
{
noteName = string.IsNullOrWhiteSpace(noteName) ? defaultFileName : noteName;
noteName = noteName.Trim().ToLower();
return Path.Combine(filePath, noteName);
}
}
}