66 lines
1.7 KiB
C#
66 lines
1.7 KiB
C#
namespace BinaryDad.Notes.Services
|
|
{
|
|
public class FileNoteService : INoteService
|
|
{
|
|
private readonly string folderPath;
|
|
|
|
private static readonly string defaultFolderPath = "notes";
|
|
|
|
public FileNoteService(IConfiguration configuration)
|
|
{
|
|
folderPath = configuration["FileNoteService:ContentFolder"];
|
|
|
|
if (string.IsNullOrWhiteSpace(folderPath))
|
|
{
|
|
folderPath = defaultFolderPath;
|
|
}
|
|
}
|
|
|
|
public string GetText(string noteName)
|
|
{
|
|
CheckFile(noteName);
|
|
|
|
return File.ReadAllText(GetFilePath(noteName));
|
|
}
|
|
|
|
public ICollection<string> GetNoteNames()
|
|
{
|
|
return Directory.GetFiles(folderPath)
|
|
.Select(f => Path.GetFileName(f))
|
|
.ToList();
|
|
}
|
|
|
|
public void SaveText(string content, string noteName)
|
|
{
|
|
File.WriteAllText(GetFilePath(noteName), content);
|
|
}
|
|
|
|
public void DeleteNote(string noteName)
|
|
{
|
|
var filePath = GetFilePath(noteName);
|
|
|
|
File.Delete(filePath);
|
|
}
|
|
|
|
private void CheckFile(string noteName)
|
|
{
|
|
var filePath = GetFilePath(noteName);
|
|
|
|
// ensure initialized
|
|
if (!File.Exists(filePath))
|
|
{
|
|
Directory.CreateDirectory(folderPath);
|
|
|
|
SaveText("Hi! Feel free to start typing. Everything will be saved soon after you are done typing.", noteName);
|
|
}
|
|
}
|
|
|
|
private string GetFilePath(string noteName)
|
|
{
|
|
noteName = noteName.Trim().ToLower();
|
|
|
|
return Path.Combine(folderPath, noteName);
|
|
}
|
|
}
|
|
}
|