private async Task<string> RollingLogFileNameAsync(IFolder folder)
{
var files = await folder.GetFilesAsync().ConfigureAwait(false);
var counter = 0;
if (files.Count > 0)
{
var logFiles = (from f in files where Regex.Match(f.Name, LOG_FILE_PATTERN).Success select f).OrderBy(f => f.Name).ToList();
if (logFiles.Count > 0)
{
//if the number of files are greater than the max number of files allowed then,
//delete the oldest file. oldest file is the file with the lowest number
while (logFiles.Count > MAX_FILES_COUNT)
{
await logFiles[0].DeleteAsync().ConfigureAwait(false);
logFiles.RemoveAt(0);
}
// the current file is the file at the zeroth index.
var currentFile = logFiles[logFiles.Count - 1];
long fileSize = 0;
using (var stream = await currentFile.OpenAsync(PCLStorage.FileAccess.Read).ConfigureAwait(false))
{
fileSize = stream.Length;
}
if (fileSize < MAX_SIZE)
{
return currentFile.Name;
}
else
{
var fileName = currentFile.Name;
var regex = new Regex(LOG_FILE_PATTERN);
var match = regex.Match(fileName);
if (match.Success)
{
if (int.TryParse(match.Groups["counter"].Value, out counter))
counter++;
}
}
}
}
return string.Format(LOG_FILE_FORMAT, counter);
}
}