Reputation: 115
I have a problem writing the file: I call the app launch via the API and get its status in string.
using System;
using System.Threading.Tasks;
using UiPath.Robot.Api;
using System.Linq;
using System.IO;
namespace RobotApi
{
class Program
{
static TextWriter sw = new StreamWriter("d:\\robo\\log.txt", true, System.Text.Encoding.Default);
static async Task Main(string[] args)
{
var client = new RobotClient();
var processes = await client.GetProcesses();
var myProcess = processes.Single(process => process.Name == "MyProcess");
var job = myProcess.ToJob();
job.StatusChanged += (sender, args) => sw.WriteLine($"{((Job)sender).ProcessKey}: {args.Status}");
await client.RunJob(job);
}
}
}
I need to write the job status to a txt file for later analysis. Since the program is called asynchronously, I can't use the StreamWritter, since it simply can't be closed. File.WriteAllText just can't handle such a flow of information and doesn't have time to close the file, as a result, I get an error message that txt is being used by another process.
Please tell me, is there a way to write a large stream of information to a txt file in my case (it is necessary that the string is overwritten with each status update)?
Upvotes: 1
Views: 109
Reputation: 59208
I believe that your problem is just with the lambda expression and you don't know how to get more statements inside it except the WriteLine()
call.
A solution would be to define a regular method instead of the lambda expression.
namespace RobotApi
{
class Program
{
// <-- removed the StreamWriter here
static async Task Main(string[] args)
{
var client = new RobotClient();
var processes = await client.GetProcesses();
var myProcess = processes.Single(process => process.Name == "MyProcess");
var job = myProcess.ToJob();
job.StatusChanged += OnStatusChanged; // <-- refer to the method here
await client.RunJob(job);
}
// This method is new
// Assuming StatusEventArgs
void OnStatusChanged(object sender, StatusEventArgs args)
{
// using will close the file
using (TextWriter sw = new StreamWriter("d:\\robo\\log.txt", true, System.Text.Encoding.Default))
{
sw.WriteLine($"{((Job)sender).ProcessKey}: {args.Status}");
}
}
}
}
This implementation is not thread safe, but your implementation wasn't either, so I don't care at the moment.
Upvotes: 2
Reputation: 46
sw (from TextWriter) is statically global to the program object... I do not see where it is being CLOSED... you write to it on the async threading calls... but never close it... never flush it...
And of course (unless I missed something) never overwrite it with a new open call... so there is never the intended overwrite????
Upvotes: 1