Skip to content

Commit

Permalink
Modify to delete file if null or empty
Browse files Browse the repository at this point in the history
  • Loading branch information
emoacht committed Jan 9, 2024
1 parent 24a4f0f commit 30c165d
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Source/Monitorian.Core/AppKeeper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private async Task ParseArgumentsAsync(StartupEventArgs e, string[] standardOpti

public Task<string> LoadArgumentsAsync() => AppDataService.ReadAsync(ArgumentsFileName);

public Task SaveArgumentsAsync(string content) => AppDataService.WriteAsync(ArgumentsFileName, false, content);
public Task SaveArgumentsAsync(string content) => AppDataService.WriteAsync(ArgumentsFileName, append: false, delete: true, content);

#endregion

Expand Down
15 changes: 14 additions & 1 deletion Source/Monitorian.Core/Models/AppDataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,23 @@ public static async Task<string> ReadAsync(string fileName)
return await sr.ReadToEndAsync();
}

public static async Task WriteAsync(string fileName, bool append, string content)
/// <summary>
/// Asynchronously writes to a specified file.
/// </summary>
/// <param name="fileName">File name to write to</param>
/// <param name="append">True to append to the file; False to overwrite the file</param>
/// <param name="delete">True to delete the file if content is null or empty; False to leave the file</param>
/// <param name="content">Content to write to the file</param>
public static async Task WriteAsync(string fileName, bool append, bool delete, string content)
{
var filePath = Path.Combine(EnsureFolderPath(), fileName);

if (delete && string.IsNullOrEmpty(content))
{
File.Delete(filePath);
return;
}

using var sw = new StreamWriter(filePath, append, Encoding.UTF8); // BOM will be emitted.
await sw.WriteAsync(content);
}
Expand Down
4 changes: 2 additions & 2 deletions Source/Monitorian.Core/Models/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ private static async Task<string[]> GetOperationFileNamesAsync()
if (fileNames.Any())
{
content += await AppDataService.ReadAsync(fileNames.First());
await AppDataService.WriteAsync(fileNames.First(), append: false, content);
await AppDataService.WriteAsync(fileNames.First(), append: false, delete: false, content);
AppDataService.Delete(OperationFileName);
}
else
Expand Down Expand Up @@ -134,7 +134,7 @@ public static async Task RecordOperationAsync(string content)

try
{
await AppDataService.WriteAsync(fileName, append: true, content);
await AppDataService.WriteAsync(fileName, append: true, delete: false, content);
}
catch (Exception ex)
{
Expand Down

0 comments on commit 30c165d

Please sign in to comment.