You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

129 lines
3.6 KiB
C#

namespace CommanderApp.Services;
public class FileOperations : IFileOperations
{
public async Task<bool> CopyAsync(string sourcePath, string targetPath, bool overwrite = true)
{
try
{
await Task.Run(() => File.Copy(sourcePath, targetPath, overwrite));
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Copy failed: {ex.Message}");
return false;
}
}
public async Task<bool> MoveAsync(string sourcePath, string targetPath, bool overwrite = true)
{
try
{
await Task.Run(() =>
{
if (File.Exists(targetPath) && overwrite)
File.Delete(targetPath);
File.Move(sourcePath, targetPath);
});
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Move failed: {ex.Message}");
return false;
}
}
public async Task<bool> DeleteAsync(string path)
{
try
{
await Task.Run(() =>
{
if (Directory.Exists(path))
Directory.Delete(path, true);
else if (File.Exists(path))
File.Delete(path);
});
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Delete failed: {ex.Message}");
return false;
}
}
public async Task<bool> CreateDirectoryAsync(string path)
{
try
{
await Task.Run(() => Directory.CreateDirectory(path));
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"CreateDirectory failed: {ex.Message}");
return false;
}
}
public async Task<bool> OpenFileAsync(string filePath)
{
try
{
await Task.Run(() =>
{
#if WINDOWS
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = filePath,
UseShellExecute = true
});
#else
var process = new System.Diagnostics.Process();
process.StartInfo.FileName = "open";
process.StartInfo.Arguments = $"\"{filePath}\"";
process.StartInfo.UseShellExecute = false;
process.Start();
#endif
});
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"OpenFile failed: {ex.Message}");
return false;
}
}
public async Task<bool> CopyDirectoryAsync(string sourceDir, string targetDir)
{
try
{
await Task.Run(() =>
{
Directory.CreateDirectory(targetDir);
foreach (var file in Directory.GetFiles(sourceDir))
{
var destFile = Path.Combine(targetDir, Path.GetFileName(file));
File.Copy(file, destFile, true);
}
foreach (var directory in Directory.GetDirectories(sourceDir))
{
var destDir = Path.Combine(targetDir, Path.GetFileName(directory));
CopyDirectoryAsync(directory, destDir).Wait();
}
});
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"CopyDirectory failed: {ex.Message}");
return false;
}
}
}