Notes/Services/FileNoteService.cs

66 lines
1.7 KiB
C#
Raw Normal View History

2023-01-05 10:32:21 -05:00
namespace BinaryDad.Notes.Services
{
public class FileNoteService : INoteService
{
2024-01-06 21:01:17 -05:00
private readonly string folderPath;
2023-01-05 10:32:21 -05:00
2024-01-06 21:01:17 -05:00
private static readonly string defaultFolderPath = "notes";
2023-01-05 10:32:21 -05:00
public FileNoteService(IConfiguration configuration)
{
2024-01-06 21:01:17 -05:00
folderPath = configuration["FileNoteService:ContentFolder"];
2024-01-06 21:01:17 -05:00
if (string.IsNullOrWhiteSpace(folderPath))
{
2024-01-06 21:01:17 -05:00
folderPath = defaultFolderPath;
}
}
2024-05-07 21:43:09 -04:00
public string GetNote(string noteName)
{
CheckFile(noteName);
return File.ReadAllText(GetFilePath(noteName));
}
public ICollection<string> GetNoteNames()
{
2024-01-06 21:01:17 -05:00
return Directory.GetFiles(folderPath)
2023-05-12 12:38:13 -04:00
.Select(f => Path.GetFileName(f))
.ToList();
2023-01-05 10:32:21 -05:00
}
2025-01-09 11:41:18 -05:00
public void SaveNote(string noteName, string content)
2023-01-05 10:32:21 -05:00
{
File.WriteAllText(GetFilePath(noteName), content);
2023-01-05 10:32:21 -05:00
}
2023-05-12 12:47:54 -04:00
public void DeleteNote(string noteName)
{
var filePath = GetFilePath(noteName);
File.Delete(filePath);
}
2023-05-17 21:44:41 -04:00
private void CheckFile(string noteName)
2023-01-05 10:32:21 -05:00
{
var filePath = GetFilePath(noteName);
// ensure initialized
if (!File.Exists(filePath))
{
2024-01-06 21:01:17 -05:00
Directory.CreateDirectory(folderPath);
2025-01-10 13:51:16 +00:00
SaveNote(noteName, "Hi! Feel free to start typing. Everything will be saved soon after you are done typing.");
}
2023-01-05 10:32:21 -05:00
}
2023-05-17 21:44:41 -04:00
private string GetFilePath(string noteName)
{
noteName = noteName.Trim().ToLower();
2024-01-06 21:01:17 -05:00
return Path.Combine(folderPath, noteName);
}
2023-01-05 10:32:21 -05:00
}
}