Ok so I completely re-wrote the code for this in an attempt to make this simpler. Now it is telling me that "Type or namespace definition, or end-of-file expected. I can only think my spacing is off or i'm missing a bracket, but when i try to add a bracket i get the same error. All I want to do is create simple wrapper for my EXE and its been very frustrating. Please if possible look at my code and tell me what i am doing wrong here. Any help is welcomed...
using System.IO;
//using Resources.resx;
namespace EXE_program
{
public class LaunchEXE
{
static void Main(string[] args)
{
string exeName = Path.Combine(Directory.GetCurrentDirectory(), "EntUpdate_v3.0.exe");
string argsLin = "";
int timeoutSeconds = 100;}
internal static string Run(string exeName, string argsLine, int timeoutSeconds)
{
StreamReader outputStream = StreamReader.Null;
string output = "";
bool success = false;
Process newProcess = new Process();
newProcess.StartInfo.FileName = exeName;
newProcess.StartInfo.Arguments = argsLine;
newProcess.StartInfo.UseShellExecute = false;
newProcess.StartInfo.CreateNoWindow = true; //The command line is supressed to keep the process in the background
newProcess.StartInfo.RedirectStandardOutput = true;
newProcess.Start();
return "\t" + output; }
}
}
}
Related
All I need is for file1 and file2 to show the text inside the file. File1 is working great! File2 not so much. I believe there is something wrong with how I wrote file2 being read. Because I made a class so that I can make file2's text go to another file called outputfile2, and even that isn't working.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace RandomName
{
class Program
{
static void Main(string[] args)
{
string winDir =
"C:/Users/RandomPerson/Desktop/RandomName/bin/Debug/";
string fileName = "file1.txt";
StreamReader reader = new StreamReader(winDir + fileName);
string outputFileName = "upperfile" + fileName;
StreamWriter writer = new StreamWriter(outputFileName);
int n = 0;
string st = "";
string upperString = "";
int n2 = 0;
string st2 = "";
string upperString2 = "";
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2;
StreamWriter writer2 = new StreamWriter(outputFileName2);
do
{
++n;
st = reader.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n + ": " + st); // write to the console
writer.WriteLine(st); // write line to disk file instead, using WriteLine() method
upperString = upperString + "\n" + st; // append each line to the big string
}
while (!reader.EndOfStream);
do
{
++n2;
st2 = reader2.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n2 + ": " + st2); // write to the
console
writer2.WriteLine(st2); // write line to disk file instead,
using WriteLine() method
upperString2 = upperString2 + "\n" + st2; // append each line
to the big string
}
while (!reader2.EndOfStream);
reader.Close();
writer.Close();
Console.WriteLine("\nHere is the entire file in a string:");
Console.WriteLine(upperString);
Console.WriteLine(upperString2);
UpperString b = new UpperString(upperString);
UpperString2 c = new UpperString2(upperString2);
Console.WriteLine("\nThe string in reverse case: ");
b.showReverseCase();
Console.WriteLine("\n");
c.readingFile2();
c.toNewFile2();
}
}
}
"b." is for another class that I have. I copied the code from that class into the "c." one, changing names of strings and such. And that didn't work. Which is why I think something is wrong somewhere in the main.
Here is the class
class UpperString2
{
private string upperString2;
public UpperString2() { }
public UpperString2(string c) { upperString2 = c; }
public void readingFile2()
{
string[] lines = System.IO.File.ReadAllLines("C:/Users/SomeName/Desktop/FolderName/bin/Debug/file2.txt");
System.Console.WriteLine("\nAnother Poem \n");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine(line);
}
}
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
I am a bit new to SteamReader and SteamWriter, which is why I think I went wrong somehow with that. I'm not sure what though. Thank you anyone who can help me have the text in file2 show up without it being overwritten by file1's text!
The problem is "outputfile2" was already opened by reader2 in Main().
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2; //<--outputfile2.txt
StreamWriter writer2 = new StreamWriter(outputFileName2)
Then it raises an exception when you try to open the same file for writting in toNewFile2():
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
This happens because the object writer2 is still alive and locking the file in Main() and there's no using statement for disposing the object when no longer needed.
Since you have moved the code to a class, call that class instead.
I want to pass Arabic string to python script from c#.
And then I will write output to txt file. But my arabic string parameter couldn't pass correctly. It transforms to "????" question marks.
I tried some code, like unicode, but it doesn't work
if __name__ == '__main__':
my_input = sys.argv[1]
out = open("C:\\output.txt", "wb")
p = unicode(my_input, encoding='utf-8')
out.write(p)
out.close()
Also my c# code is like that
public static string run_cmd(string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:/Python27/python.exe";
start.Arguments = "C:/test.py" + " " + args;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
result = reader.ReadToEnd();
}
}
}
Do you have any idea how can I fix this problem?
Or is there something that I missing?
Any idea will be great!
I'm trying to run a Python script from C# as a stream, and to repeatedly pass inputs and outputs between Python and the stream, using StreamWriter and StreamReader.
I can read and write, but apparently only once, and not multiple times. (Which is what I need.)
Hopefully, somebody can tell me what I'm doing wrong.
(I'm aware that I can probably do what I need to do by reading and writing to a file. However, I'd like to avoid this if I can, since using the Stream seems cleaner.)
Here's my C# code:
using System;
using System.Diagnostics;
using System.IO;
public class Stream_Read_Write
{
public static void Main()
{
string path = "C:\\Users\\thomas\\Documents\\Python_Scripts\\io_test.py";
string iter = "3";
string input = "Hello!";
stream_read_write(path, iter, input);
//Keep Console Open for Debug
Console.Write("end");
Console.ReadKey();
}
private static void stream_read_write(string path, string iter, string input)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
start.Arguments = string.Format("{0} {1}", path, iter);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.CreateNoWindow = true;
using (Process process = Process.Start(start))
using (StreamWriter writer = process.StandardInput)
using (StreamReader reader = process.StandardOutput)
{
for (int i = 0; i < Convert.ToInt32(iter); i++)
{
Console.WriteLine("writing...");
writer.WriteLine(input);
writer.Flush();
Console.WriteLine("written: " + input + "\n");
Console.WriteLine("reading...");
string result = reader.ReadLine();
Console.WriteLine("read: " + result + "\n");
}
}
}
}
The Python code looks like this:
import sys
iter = int(sys.argv[1])
for i in range(iter):
input = raw_input()
print (input)
And this is the output that I get:
writing...
written: Hello!
reading...
Strangely, when I remove the loops from both Python and C#, it works.
(For one iteration)
writing...
written: Hello!
reading...
read: Hello!
end
It's not clear to me why this happens, or what the solution could be, so any help is much appreciated.
I found a solution to my problem. I'm not really sure why this works, though.
For C#:
using System;
using System.Diagnostics;
using System.IO;
public class Stream_Read_Write
{
public static void Main()
{
string path = "C:\\Users\\thomas_wortmann\\Documents\\Python_Scripts\\io_test.py";
string iter = "3";
string input = "Hello";
stream_read_write(path, iter, input);
//Keep Console Open for Debug
Console.Write("end");
Console.ReadKey();
}
private static void stream_read_write(string path, string iter, string input)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
start.Arguments = string.Format("{0} {1}", path, iter);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.CreateNoWindow = true;
using (Process process = Process.Start(start))
using (StreamWriter writer = process.StandardInput)
using (StreamReader reader = process.StandardOutput)
{
for (int i = 0; i < Convert.ToInt32(iter); i++)
{
writer.WriteLine(input + i);
Console.WriteLine("written: " + input + i);
string result = null;
while (result == null || result.Length == 0)
{ result = reader.ReadLine(); }
Console.WriteLine("read: " + result + "\n");
}
}
}
}
And the python code looks like this:
import sys
def reverse(input):
return input [::-1]
iter = int(sys.argv[1])
for i in range(iter):
input = sys.stdin.readline()
print reverse(input)
sys.stdout.flush()
This is a conventional stream problem.
You have to “flush” the stream
(e.g. stdout.flush() , where stdout is a stream object)
in order to send the data
no matter in C# or in Python.
In C#, as I know, you have to execute stream.Close()
to complete the flush itself,
or you can wrap the stream with “using”
and it send the data when the brackets is closed.
Edit:
Btw, the stream is only available to one side at a time.
I want to do what I wrote in the title. But I just simply can't get my head around it. I also googled everythng. I want to write strings to file of special type FIFO, created by mkfifo (I think). If there are any other suggestions how to do this, you are welcome.
static class PWM
{
static string fifoName = "/dev/pi-blaster";
static FileStream file;
static StreamWriter write;
static PWM()
{
file = new FileInfo(fifoName).OpenWrite();
write = new StreamWriter(file, Encoding.ASCII);
}
//FIRST METHOD
public static void Set(int channel, float value)
{
string s = channel + "=" + value;
Console.WriteLine(s);
write.Write(s);
// SECOND METHOD
// RunProgram(s);
}
//SECOND METHOD
static void RunProgram(string s)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = true;
proc.StartInfo.FileName = "bash";
string x = "|echo " +s+" > /dev/pi-blaster";
Console.WriteLine(x);
proc.StartInfo.Arguments = x;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
// proc.WaitForExit();
}
}
SOLUTION!!!! PI-BLASTER WORKS :D :D (lost 2 days of life because of this)
write.flush was critical, btw.
namespace PrototypeAP
{
static class PWM
{
static string fifoName = "/dev/pi-blaster";
static FileStream file;
static StreamWriter write;
static PWM()
{
file = new FileInfo(fifoName).OpenWrite();
write = new StreamWriter(file, Encoding.ASCII);
}
//FIRST METHOD
public static void Set(int channel, float value)
{
string s = channel + "=" + value + "\n";
Console.WriteLine(s);
write.Write(s);
write.Flush();
}
}
}
i edited my code to the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Search
{
class Program
{
static void Main(string[] args)
{
string abc = string.Format("{0}", args[0]);
string latestversion = string.Format("{1}", args[1]);
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "sslist.exe";
p.StartInfo.Arguments = "-R -H -h sinsscm01.ds.net" + type;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
string procOutput = p.StandardOutput.ReadToEnd();
string procError = p.StandardError.ReadToEnd();
TextWriter outputlog = new StreamWriter("C:\\Work\\listofsnapshot.txt");
outputlog.Write(procOutput);
outputlog.Close();
string greatestVersionNumber = "";
using (StreamReader sr = new StreamReader("C:\\Work\\listofsnapshot.txt"))
{
while (sr.Peek() >= 0)
{
var line = sr.ReadLine();
var versionNumber = line.Replace(latestversion, "");
if(versionNumber.Length != line.Length)
greatestVersionNumber = versionNumber;
}
}
Console.WriteLine(greatestVersionNumber);
TextWriter latest = new StreamWriter("C:\\Work\\latestbuild.properties");
latest.Write("Version_Number=" + greatestVersionNumber);
latest.Close();
}
}
}
where string type and string latest version are the arguments parsed.
So, my commandline looks like this:
c:/searchversion.exe "/SASE Lab Tools" "6.70_Extensions/6.70.102/ANT_RELEASE_"
where "/SASE Lab Tools" should be stored as a string abc and "6.70_Extensions/6.70.102/ANT_RELEASE_" should be stored as a string as latestversion.
However i get an error: System.Format.Exception: Index(zero based) must be greater than or equal to zero and less than the size of the argument list at line 14:
string latestversion = string.Format("{1}", args[1]);
Anybody knows whats wrong?
string latestversion = string.Format("{0}", args[0]);
updated
if you go debugging do you have your args[] filled with data?
for
string latestversion = string.Format("{1}", args[1]);
You specified the 2nd item in the array of the string format, for which there isnt one. So the array is out of bounds. you meant
string latestversion = string.Format("{0}", args[1]);
See abc and latestversion are two different strings. And since you are formatting those one-by-one, you need to start your format specifiers by 0 each time. So, your code should be:
string latestversion = string.Format("{0}", args[1]);