async/background TryDeleteIfExistsAsync & DeleteContentsOfDir

This commit is contained in:
N00MKRAD
2021-05-09 18:31:39 +02:00
parent b3a32ff557
commit f9a631340d
7 changed files with 72 additions and 84 deletions

View File

@@ -118,18 +118,29 @@ namespace Flowframes.IO
}
}
public static void DeleteContentsOfDir(string path)
/// <summary>
/// Async version of DeleteContentsOfDir, won't block main thread.
/// </summary>
public static async Task<bool> DeleteContentsOfDirAsync(string path)
{
DirectoryInfo directoryInfo = new DirectoryInfo(path);
FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo fileInfo in files)
{
fileInfo.Delete();
return await Task.Run(async () => { return DeleteContentsOfDir(path); }); // Delete in background thread
}
DirectoryInfo[] directories = directoryInfo.GetDirectories();
foreach (DirectoryInfo directoryInfo2 in directories)
/// <summary>
/// Delete everything inside a directory except the dir itself.
/// </summary>
public static bool DeleteContentsOfDir(string path)
{
directoryInfo2.Delete(recursive: true);
try
{
DeleteIfExists(path);
Directory.CreateDirectory(path);
return true;
}
catch(Exception e)
{
Logger.Log("DeleteContentsOfDir Error: " + e.Message, true);
return false;
}
}
@@ -245,36 +256,6 @@ namespace Flowframes.IO
}
}
public static async Task<Dictionary<string, string>> RenameCounterDirReversibleAsync(string path, string ext, int startAt, int padding = 0)
{
Stopwatch sw = new Stopwatch();
sw.Restart();
Dictionary<string, string> oldNewNamesMap = new Dictionary<string, string>();
int counter = startAt;
FileInfo[] files = new DirectoryInfo(path).GetFiles($"*.{ext}", SearchOption.TopDirectoryOnly);
var filesSorted = files.OrderBy(n => n);
foreach (FileInfo file in files)
{
string dir = new DirectoryInfo(file.FullName).Parent.FullName;
int filesDigits = (int)Math.Floor(Math.Log10((double)files.Length) + 1);
string newFilename = (padding > 0) ? counter.ToString().PadLeft(padding, '0') : counter.ToString();
string outpath = outpath = Path.Combine(dir, newFilename + Path.GetExtension(file.FullName));
File.Move(file.FullName, outpath);
oldNewNamesMap.Add(file.FullName, outpath);
counter++;
if(sw.ElapsedMilliseconds > 100)
{
await Task.Delay(1);
sw.Restart();
}
}
return oldNewNamesMap;
}
public static async Task ReverseRenaming(string basePath, Dictionary<string, string> oldNewMap) // Relative -> absolute paths
{
Dictionary<string, string> absPaths = oldNewMap.ToDictionary(x => Path.Combine(basePath, x.Key), x => Path.Combine(basePath, x.Value));
@@ -347,8 +328,10 @@ namespace Flowframes.IO
public static async Task<Size> GetVideoOrFramesRes (string path)
{
Size res;
Size res = new Size();
try
{
if (!IsPathDirectory(path)) // If path is video
{
res = GetVideoRes(path);
@@ -357,6 +340,11 @@ namespace Flowframes.IO
{
Image thumb = await MainUiFunctions.GetThumbnail(path);
res = new Size(thumb.Width, thumb.Height);
}
}
catch (Exception e)
{
Logger.Log("GetVideoOrFramesRes Error: " + e.Message);
}
return res;
@@ -379,12 +367,30 @@ namespace Flowframes.IO
return size;
}
/// <summary>
/// Async (background thread) version of TryDeleteIfExists. Safe to run without awaiting.
/// </summary>
public static async Task<bool> TryDeleteIfExistsAsync(string path)
{
string renamedPath = path;
while (Directory.Exists(renamedPath)) // Keep adding a "_" to the end if there is still an undeleted dir (unlikely)
renamedPath += "_";
Directory.Move(path, renamedPath); // Move/rename, so a new folder can be created without waiting this one's deletion
return await Task.Run(async () => { return TryDeleteIfExists(renamedPath); }); // Delete in background thread
}
/// <summary>
/// Delete a path if it exists. Works for files and directories. Returns success status.
/// </summary>
public static bool TryDeleteIfExists(string path) // Returns true if no exception occurs
{
try
{
if (path == null)
return false;
DeleteIfExists(path);
return true;
}
@@ -397,16 +403,20 @@ namespace Flowframes.IO
public static bool DeleteIfExists (string path) // Returns true if the file/dir exists
{
Logger.Log($"DeleteIfExists({path})", true);
if (!IsPathDirectory(path) && File.Exists(path))
{
File.Delete(path);
return true;
}
if (IsPathDirectory(path) && Directory.Exists(path))
{
Directory.Delete(path, true);
return true;
}
return false;
}

View File

@@ -100,12 +100,12 @@ namespace Flowframes.Main
}
if (!stepByStep)
IOUtils.DeleteContentsOfDir(I.current.interpFolder);
await IOUtils.DeleteContentsOfDirAsync(I.current.interpFolder);
}
static async Task CopyOutputFrames(string framesPath, string framesFile, string outputFolderPath, bool dontMove)
{
IOUtils.TryDeleteIfExists(outputFolderPath);
await IOUtils.TryDeleteIfExistsAsync(outputFolderPath);
IOUtils.CreateDir(outputFolderPath);
Stopwatch sw = new Stopwatch();
sw.Restart();

View File

@@ -242,11 +242,11 @@ namespace Flowframes
{
DialogResult dialogResult = MessageBox.Show($"Delete the temp folder (Yes) or keep it for resuming later (No)?", "Delete temporary files?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
IOUtils.TryDeleteIfExists(current.tempFolder);
Task.Run(async () => { await IOUtils.TryDeleteIfExistsAsync(current.tempFolder); });
}
else
{
IOUtils.TryDeleteIfExists(current.tempFolder);
Task.Run(async () => { await IOUtils.TryDeleteIfExistsAsync(current.tempFolder); });
}
}
@@ -266,7 +266,7 @@ namespace Flowframes
Logger.Log("Deleting temporary files...");
try
{
Directory.Delete(current.tempFolder, true);
await Task.Run(async () => { Directory.Delete(current.tempFolder, true); });
}
catch (Exception e)
{

View File

@@ -58,7 +58,7 @@ namespace Flowframes.Main
// if (Config.GetBool("scnDetect") && !current.inputIsFrames) // Input is video - extract frames first
// await ExtractSceneChanges();
if (!IOUtils.TryDeleteIfExists(current.framesFolder))
if (!(await IOUtils.TryDeleteIfExistsAsync(current.framesFolder)))
{
InterpolateUtils.ShowMessage("Failed to delete existing frames folder - Make sure no file is opened in another program!", "Error");
return;
@@ -81,7 +81,7 @@ namespace Flowframes.Main
InterpolateUtils.ShowMessage("There are no extracted frames that can be interpolated!\nDid you run the extraction step?", "Error");
return;
}
if (!IOUtils.TryDeleteIfExists(current.interpFolder))
if (!(await IOUtils.TryDeleteIfExistsAsync(current.interpFolder)))
{
InterpolateUtils.ShowMessage("Failed to delete existing frames folder - Make sure no file is opened in another program!", "Error");
return;

View File

@@ -46,7 +46,7 @@ namespace Flowframes.Media
await RunFfmpeg(args, LogMode.Hidden);
if (deleteAlphaDir)
IOUtils.TryDeleteIfExists(alphaDir);
await IOUtils.TryDeleteIfExistsAsync(alphaDir);
}
}
}

View File

@@ -48,7 +48,7 @@ namespace Flowframes.Media
if (IOUtils.GetFilesize(outPath) < 512)
{
Logger.Log($"Failed to extract audio stream #{track.streamIndex}, even with re-encoding. Will be missing from output.");
IOUtils.TryDeleteIfExists(outPath);
await IOUtils.TryDeleteIfExistsAsync(outPath);
return;
}
@@ -120,7 +120,7 @@ namespace Flowframes.Media
}
else
{
IOUtils.TryDeleteIfExists(outPath); // Delete if encode was not successful
await IOUtils.TryDeleteIfExistsAsync(outPath); // Delete if encode was not successful
}
}
@@ -313,28 +313,6 @@ namespace Flowframes.Media
await RunFfmpeg(args, tempFolder, LogMode.Hidden);
// if (File.Exists(outPath) && IOUtils.GetFilesize(outPath) < 1024)
// {
// Logger.Log("Failed to merge audio losslessly! Trying to re-encode.", false, false, "ffmpeg");
//
// args = $" -i {inName} -stream_loop {looptimes} -i {audioName.Wrap()}" +
// $"{trackInputArgs} -map 0:v -map 1:a {trackMapArgs} -c:v copy {Utils.GetAudioFallbackArgs(Path.GetExtension(inputFile))} -c:s {subCodec} {trackMetaArgs} -shortest {outName}";
//
// await RunFfmpeg(args, tempFolder, LogMode.Hidden);
//
// if (File.Exists(outPath) && IOUtils.GetFilesize(outPath) < 1024)
// {
// Logger.Log("Failed to merge audio, even with re-encoding. Output will not have audio.", false, false, "ffmpeg");
// IOUtils.TryMove(tempPath, inputFile); // Move temp file back
// IOUtils.TryDeleteIfExists(tempPath);
// return;
// }
//
// string audioExt = Path.GetExtension(audioPath).Remove(".").ToUpper();
// Logger.Log($"Source audio ({audioExt}) has been re-encoded to fit into the target container ({containerExt.Remove(".").ToUpper()}). This may decrease the quality slightly.", false, true, "ffmpeg");
// }
if (File.Exists(outPath) && IOUtils.GetFilesize(outPath) > 512)
{
File.Delete(tempPath);

View File

@@ -291,7 +291,7 @@ namespace Flowframes
string lastInterpPath = outPath + $"-run{iteration - 1}";
Directory.Move(outPath, lastInterpPath); // Rename last interp folder
await RunRifeNcnnProcess(lastInterpPath, outPath, mdl);
IOUtils.TryDeleteIfExists(lastInterpPath);
await IOUtils.TryDeleteIfExistsAsync(lastInterpPath);
}
else
{