Notes/Services/FileNoteService.cs

63 lines
1.7 KiB
C#
Raw Normal View History

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