I have client-server application developed in C#.NET 3.5. This application uses 3 programs to complete the required work. Process A(Server) and Process B(remote launcher) are developed in .NET and Process C is a third party console application whose development language is not known. Using the Administrative credentials of remote computer, Process A copies Process B on that and schedules Process B as task on remote computer. After this, Process B starts by task scheduler and it creates log.txt
file to log the messages. Then Process B starts Process C using Process.Start()
semantics and redirects its standard output and error
to write into log.txt
file. Process A uses Process.GetProcesses(remotecomputername)
semantics to monitor whether Process C is still running on remote computer.
Process A is also reading the log.txt
file using network share read like \\RemoteComputerName\C$\RemoteDir\log.txt
and displaying the messages on its window.
My issue is, all the output and error are not getting logged on log.txt
. And Process A is not able to read correctly from log.txt
. If the output/error logged using DebugView they are getting logged correctly.Is this synchronization/access rights issue? How to get rid of it?
Any pointers/hints will be truly valuable. Unable to share full code due to restrictions.
Sample code given below
Process A
//Below method is called every 2 seconds from Server to read new messages.
//path passed as `\\RemoteComputerName\C$\RemoteDir\log.txt`
private void ReadRemoteLog(string path)
{
try
{
string[] lines = File.ReadAllLines(path);
while (RemoteLogPosition < lines.LongLength)
{
string msg = lines[RemoteLogPosition].Trim();
if (!string.IsNullOrEmpty(msg))
{
Trace.WriteLine("# " +msg); //Writing on DebugView
OnProgressChanged(msg);
}
RemoteLogPosition++; //This is global variable to keep track of last read position.
}
}
}
Process B's code for starting Process C
ProcessStartInfo ps = new ProcessStartInfo();
ps.UseShellExecute = false;
ps.FileName = <Path to process C>;
ps.Arguments = <Commandline args to Process C>;
ps.WorkingDirectory = @"C:\RemoteDir";
ps.RedirectStandardError = true;
ps.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = ps;
p.OutputDataReceived += (s, e) => { WriteLog(e.Data.Trim());};
p.ErrorDataReceived += (s, e) => { WriteLog(e.Data.Trim()); };
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
WriteLog("Process Started - "+ps.FileName + ps.Arguments);
p.WaitForExit();
Process B's WriteLog Method -
private void WriteLog(string message)
{
using (FileStream fs = new FileStream(@"C:\\RemoteDir\log.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Inheritable))
using(StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine("#" + message);
}
}