using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Artemis.Core { /// /// Represents a plugin prerequisite action that copies a folder /// public class WriteBytesToFileAction : PluginPrerequisiteAction { /// /// Creates a new instance of a copy folder action /// /// The name of the action /// The target file to write to (will be created if needed) /// The contents to write public WriteBytesToFileAction(string name, string target, byte[] content) : base(name) { Target = target; ByteContent = content ?? throw new ArgumentNullException(nameof(content)); } /// /// Gets or sets the target file /// public string Target { get; } /// /// Gets or sets a boolean indicating whether or not to append to the file if it exists already, if set to /// the file will be deleted and recreated /// public bool Append { get; set; } = false; /// /// Gets the bytes that will be written /// public byte[] ByteContent { get; } /// public override async Task Execute(CancellationToken cancellationToken) { string outputDir = Path.GetDirectoryName(Target)!; Utilities.CreateAccessibleDirectory(outputDir); ShowProgressBar = true; Status = $"Writing to {Path.GetFileName(Target)}..."; if (!Append && File.Exists(Target)) File.Delete(Target); await using Stream fileStream = File.OpenWrite(Target); await using MemoryStream sourceStream = new(ByteContent); await sourceStream.CopyToAsync(sourceStream.Length, fileStream, Progress, cancellationToken); ShowProgressBar = false; Status = $"Finished writing to {Path.GetFileName(Target)}"; } } }