using System.ComponentModel.DataAnnotations; using FileFlows.BasicNodes; using FileFlows.Plugin; using FileFlows.Plugin.Attributes; namespace BasicNodes.File; /// /// A flow element that writes text to a file /// public class WriteText : Node { /// public override int Inputs => 1; /// public override int Outputs => 1; /// public override FlowElementType Type => FlowElementType.Process; /// public override string Icon => "fas fa-file-signature"; /// public override string Group => "File"; /// public override string HelpUrl => "https://fileflows.com/docs/plugins/basic-nodes/write-text"; /// /// Gets or sets the output text location /// [TextVariable(1)] [Required] public string File { get; set; } /// /// Gets or sets the text to write, if blank writes the current file /// [TextVariable(2)] public string Text { get; set; } /// public override int Execute(NodeParameters args) { string file = args.ReplaceVariables(File, stripMissing: true); if (string.IsNullOrWhiteSpace(file)) { args.FailureReason = "No file set"; args.Logger?.ELog(args.FailureReason); return -1; } string text = GetText(args, Text, file); args.Logger?.ILog($"Text: {text}"); args.Logger?.ILog($"File: {file}"); var result = args.FileService.FileAppendAllText(file, text + Environment.NewLine); if (result.Failed(out var error)) { args.FailureReason = "File writing file: " + error; args.Logger.ELog(args.FailureReason); return -1; } args.Logger?.ILog($"Text written to file"); return 1; } /// /// Gets the text to write /// /// the node parameters /// the original text /// the file to write to /// the text to write public static string GetText(NodeParameters args, string text, string outputFile) { if (outputFile?.ToLowerInvariant().EndsWith(".csv") == true) { var parts = text?.Split([";", ","], StringSplitOptions.RemoveEmptyEntries) ?? []; if (parts.Length == 0) { return CsvEncode(args.WorkingFile); } return string.Join(",", parts.Select(x => CsvEncode(args.ReplaceVariables(x, stripMissing: true)))); } return args.ReplaceVariables(text, stripMissing: true)?.EmptyAsNull() ?? args.WorkingFile; } /// /// CSV encodes a string /// /// the text to encode /// the CSV encoded string private static string CsvEncode(string text) => $"\"{text.Replace("\"", "\"\"")}\""; }