Calling a program in C# Program using VisualStudio - c#

I made a CMD program that can convert the photos from Png to SVG format.
how can I call this program in a C# program?
the Photo Path is:
`var path = #"C:\Users\";
var sourcePath = Path.Combine(path, #"emoji1.png");
var destPath = Path.Combine(path, #"png01.svg");`
i would like to open my cmd Photo converter Program in other C# Program`

var arguments = ""; //optional, if your cmd converter can accept path to photo as an argument - you can put it here
var proc = Process.Start("path to executable", arguments);
proc.WaitForExit();// if you need to work in sync with that app

Related

How to create file text in "AppData\Roaming" for any user in C#

I'd like save date my app but I'm not knowing if app save for different users, Example if "andy" I can't use ("C:\Users\Game maker\AppData\Roaming") ,So How to create file in "AppData\Roaming\MaxrayStudyApp" for any user .
Computer myComputer = new Computer();
myComputer.FileSystem.WriteAllText(#"C:\Users\Game maker\AppData\Roaming\MaxrayStudy\data.txt","", false);
Almost a duplicate of this one: Environment.SpecialFolder.ApplicationData returns the wrong folder
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
That should get the folder you need then use Path.Combine() to write to a directory in that folder.
var roamingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filePath = Path.Combine(roamingDirectory, "MaxrayStudy\\data.txt");
I restart my windows and I write this
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
filePath= (filePath+#"\MaxrayStudyApp\data.txt");
string path =Convert.ToString(filePath);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(filePath,false)){
file.WriteLine(" XP : 0");}

Trying to get ironpython to create a text file that I can store info in

I'm writing a gui for ironpython and I'm trying create a text file that the user can name in a textbox. The textfile is being used to give me a python script from a vector file. Any suggestions
With the following I was able to create a file with IronPython
ScriptEngine m_engine = Python.CreateEngine();
ScriptScope m_scope = m_engine.CreateScope();
String code = #"file = open('myfile.txt', 'w+')";
ScriptSource source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatement);
source.Execute(m_scope);
Here's the Python documentation about the w+. It opens the file for writing, truncating the file first.
So I guess you just need to insert the name of the file in the script...
I am putting up the code that worked for me when I was writing in python. Hope it helps.
def on_save_as(self, sender, e):
dlg = SaveFileDialog()
dlg.Filter = "Text File (*.txt)|*.txt"
dlg.Title = "SaveFile"
if dlg.ShowDialog():
self.save_file(dlg.FileName)
def save_file(self, filename):
sw = StreamWriter(filename)
try:
buf = self.textbox.Text
sw.Write(buf)
self.statusbar_item.Content = Path.GetFileName(filename)
self.openfile = filename
except Exception, ex:
MessageBox.Show(ex.Message)
finally:
sw.Close()

Pass more arguments to an already opened cmd prompt in C#

I want to loop through all images in a folder, retrieve each image's name and pass an argument using the name. This is what I have:
foreach (string imageFile in Directory.EnumerateFiles(filePath))
{
//Get image name and save it as string
string args = "something"; //a line of argument with image name in it
Process.Start("cmd", #"/c cd C:\Tesseract-OCR && " + args);
}
The problem with above code is that, for each image file, it will open up a new command prompt. Instead, I want something like:
Process.Start("cmd", #"/k cd C:\Tesseract-OCR");
foreach (string imageFile in Directory.EnumerateFiles(filePath))
{
//For each imageFile I have, pass an argument to the opened cmd prompt
}
There are a few methods, but generally the simplest is to create a batch file with all of the commands you want to execute then pass that as a parameter to cmd.
Something like this:
string imageFolder = #"C:\Path\To\Images";
string batchFile = #"C:\Temp\cmds.cmd";
string outputFile = #"C:\Temp\cmds.log";
// substitute your own command here. "{0}" will be substituted for filename
string command = #"attrib ""{0}"" >> """ + outputFile + #"""";
// delete the batch file if it exists
if (File.Exists(batchFile))
File.Delete(batchFile);
// create batch file from content of image folder
using (var writer = File.CreateText(batchFile))
{
writer.WriteLine("#echo off");
foreach (var file in Directory.EnumerateFiles(imageFolder, "*.jpg"))
writer.WriteLine(command, file);
}
// Delete the output file if it exists
if (File.Exists(outputFile))
File.Delete(outputFile);
// Execute the batch
var p = Process.Start("cmd", #"/c """ + batchFile + #"""");
p.WaitForExit();
After that completes you can grab the content of the output file and parse it for results. If you need a break between the outputs, just echo something distinctive between each one. Maybe something like:
// create batch file from content of image folder
using (var writer = File.CreateText(batchFile))
{
writer.WriteLine("#echo off");
foreach (var file in Directory.EnumerateFiles(imageFolder, "*.jpg"))
{
writer.WriteLine(#"echo -----Start: {0}>>""{1}""", file, outputFile);
writer.WriteLine(command, file);
writer.WriteLine(#"echo -----End: {0}>>""{1}""", file, outputFile);
}
}
That way you get the filename in the output as well to help with parsing.
Another option is to use full stream redirection to streams that you can write commands to and read responses from. This would allow you to have a command prompt running somewhere in the background that you can issue commands to. Seems simple, but honestly it takes a lot of work to get just right. If you want to go this way I'd suggest redirecting all three standard streams.
Why not have the program create a batch file containing all the files/commands to be executed, then use Process.Start to execute the batch file?
You can use Directory.GetFiles() to get a string array of all the files in a directory. Then use String.Join() to merge the array into one long string of file names separated by space. I would also wrap each item in quotes if your path or files contain spaces.
const string QUOTE = "\"";
const string SPACE = " ";
const string SEPARATOR = QUOTE + SPACE + QUOTE;
string[] files = Directory.GetFiles(filePath, "*.png");
string allFiles = QUOTE + String.Join(SEPARATOR, files) + QUOTE;
Console.WriteLine(#"cmd.exe /c cd C:\Tesseract-OCR && " + allFiles);

Access file in Resources C#

I would like to import to registry a .reg file that exist in project resources.
The way to import a reg file uses the path to the reg file:
Process proc = new Process();
proc = Process.Start("regedit.exe", "/s " + "path\to\file.reg");
Is it possible to do so with a file from resources? how do I get its path?
If it is in the project folder. i-e. The folder in which the project is runnung. you can access it directly : Process.Start("regedit.exe", "/s " + "Filename.reg");
you can get the current path by using
string path =System.AppDomain.CurrentDomain.BaseDirectory; // this will give u the path for debug folder
or
string projectPath= Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())); //This will give u the project path.
you can use both and navigate arround to get the path to your desired folder. eg if you want to access a file in the Resource folder inside the project folder u can use projectPath+"\\Resource\\filename.reg"
If the file is embedded resource (and as such is not created on disk), it is best to read it like this and save it to a temporary file using:
var path = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(), "reg");
Process.Start(path);
It may not be necessary to change the extension if you don't start the file directly but use Process.Start("regedit", "/s " + path) like you described in your question. Keep in mind that the file path should be escaped so it's parsed properly as the command line argument, temporary file path, though, will not contain spaces, so it should be okay.
This is not tested code, but you get the steps I hope:
Process proc = new Process();
proc.StartInfo.FileName = "regedit.exe";
proc.StartInfo.Arguments = "/s";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
StreamWriter stdin = myProcess.StandardInput;
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "<regfile>";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
stdin.Write(reader.ReadToEnd());
}

function has stopped working" Error in running the code

I have a windows form application which works with text file data sets that I tried to make portable (ie: To run the application from external hard drive or pen drive does not need to copy the data sets into the C:\ drive directly.
I changed
StreamReader fileitem = new StreamReader("c:\\dataset.txt");
into
StreamReader fileitem = new StreamReader("dataset.txt");
and copy the dataset into the exe file path (.../bin/debug)
But it shows an error "function has stopped working"!
Any idea?
Here's a sample of how you can get the absolute path to your executable file:
static public string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Sample taken from this answer
If you implement this property you can then update your code to the following:
StreamReader fileitem = new StreamReader(AssemblyDirectory + "dataset.txt");

Categories

Resources