Notes/Services/FileNoteService.cs

66 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
{
2024-01-07 02:01:17 +00:00
private readonly string folderPath;
2023-01-05 15:32:21 +00:00
2024-01-07 02:01:17 +00:00
private static readonly string defaultFolderPath = "notes";
2023-01-05 15:32:21 +00:00
public FileNoteService(IConfiguration configuration)
{
2024-01-07 02:01:17 +00:00
folderPath = configuration["FileNoteService:ContentFolder"];
2024-01-07 02:01:17 +00:00
if (string.IsNullOrWhiteSpace(folderPath))
{
2024-01-07 02:01:17 +00:00
folderPath = defaultFolderPath;
}
}
2023-05-18 01:44:41 +00:00
public string GetText(string noteName)
{
CheckFile(noteName);
return File.ReadAllText(GetFilePath(noteName));
}
public ICollection<string> GetNoteNames()
{
2024-01-07 02:01:17 +00:00
return Directory.GetFiles(folderPath)
2023-05-12 16:38:13 +00:00
.Select(f => Path.GetFileName(f))
.ToList();
2023-01-05 15:32:21 +00:00
}
2023-05-18 01:44:41 +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-18 01:44:41 +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))
{
2024-01-07 02:01:17 +00:00
Directory.CreateDirectory(folderPath);
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
}
2023-05-18 01:44:41 +00:00
private string GetFilePath(string noteName)
{
noteName = noteName.Trim().ToLower();
2024-01-07 02:01:17 +00:00
return Path.Combine(folderPath, noteName);
}
2023-01-05 15:32:21 +00:00
}
}