C# How to get the PATH of the embedded .exe file - c#

I have an exe file which I run through windows command prompt and give command line arguments. I went through this post and ran the following command:
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
But all it did, is to give me resource files located in WindowsFormsApplication1\obj\Debug folder
I went through this post but it tells on how to execute the exe directly without the running it from cmd.
I even tried the following command:
string path = Path.Combine(Path.GetTempPath(), "MyApplication.exe");
It worked but after clearing my C:\Users\UserName\AppData\Local\Temp folder the application started giving an error.
I even tried the following command:
global::ApplicationName.Properties.Resources.MyApplication
but it gives byte[] and not the path to the application.
All I want to know is how to run the application which is embedded in my resources so that I can successfully execute the following command:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/K " + MyApplication+" Argument "+Path1+" "+Path2 ,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadToEnd();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(resultFile))
{
file.WriteLine(line);
}
}

Extract the resource into a file in the filesystem and then run it.
byte[] fileContents = ApplicationName.Properties.Resources.MyApplication;
File.WriteAllBytes("MyApplication.exe", fileContents);
Now you can run the file using MyApplicaton.exe as path.

Related

Calling WSL bash.exe from C#

Mostly just as a curiosity, I wrote a little app to start up Terminator shell on Windows, using Ubuntu/WSL and Xming window server.
Doing things manually from the shell, I can run Firefox, gedit, Terminator, etc on Windows, it's pretty cool.
So I checked the location of bash.exe using where bash and it returned...
C:\Windows\System32\bash.exe
However when I tried to run this code...
using (var xminProc = new Process())
{
xminProc.StartInfo.FileName = #"C:\Program Files (x86)\Xming\Xming.exe";
xminProc.StartInfo.Arguments = ":0 -clipboard -multiwindow";
xminProc.StartInfo.CreateNoWindow = true;
xminProc.Start();
}
using (var bashProc = new Process())
{
bashProc.StartInfo.FileName = #"C:\Windows\System32\bash.exe";
bashProc.StartInfo.Arguments = "-c \"export DISPLAY=:0; terminator; \"";
bashProc.StartInfo.CreateNoWindow = true;
bashProc.Start();
}
I get the error...
System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
And checking my entire system for bash.exe reveals it really be in another place altogether...
I'm not sure if this location is one that I can rely on, I'm worried it's ephemeral and can change during a Windows Store update, although I may be wrong about that.
Why does the command prompt show bash.exe to be in System32 but it's really in another location altogether?
Can I get C# to also use the System32 location?
As #Biswapriyo stated first set the platafrom to x64 on your solution:
Then you may run on your ubuntu machine from c# as:
Console.WriteLine("Enter command to execute on your Ubuntu GNU/Linux");
var commandToExecute = Console.ReadLine();
// if command is null use 'ifconfig' for demo purposes
if (string.IsNullOrWhiteSpace(commandToExecute))
{
commandToExecute = "ifconfig";
}
// Execute wsl command:
using (var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #"cmd.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
CreateNoWindow = true,
}
})
{
proc.Start();
proc.StandardInput.WriteLine("wsl " + commandToExecute);
System.Threading.Thread.Sleep(500); // give some time for command to execute
proc.StandardInput.Flush();
proc.StandardInput.Close();
proc.WaitForExit(5000); // wait up to 5 seconds for command to execute
Console.WriteLine(proc.StandardOutput.ReadToEnd());
Console.ReadLine();
}

File Not Found when Executing batch file

I am trying to execute a batch file which directs 7zip to compress a directory. The batch file is working fine when I run it by 'double-clicking' the file or if I try to run it in the command Prompt. But I am having problem while I am try to execute the file through a C# application. Below is my code in C#.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
path = path.Substring(0, path.IndexOf("Debug") + 6) + "Scripts";
String EnvironmentPath = System.Environment
.GetEnvironmentVariable("path",
EnvironmentVariableTarget.Machine);
string[] varList = EnvironmentPath.Split(';');
string enviVar= varList.First(x=>x.Contains("7-Zip"));
Process proc = new Process();
proc = new Process();
proc.StartInfo.WorkingDirectory = path;
proc.StartInfo.Arguments = enviVar;
proc.StartInfo.FileName = "Script_To_BackUp_DB.bat";
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
The value in path variable is : D:\Projects\Common\common\Common\Utilities\Utilities\bin\Debug\Scripts.
If I remove the "proc.StartInfo.UseShellExecute = false" line, then batch will execute and close with an exception stating 7z is not recognized as Internal or external command. And I have already set the path in Environment Variable.
The batch file code is:
set backup_dir=C:\Users\FU386DKH\Desktop\Card logs\
set db_dir=D:\Projects\Projects\db\
:: set dt string in dd_mm_yy_HH_MM_SS format
set dt=%Date:~0,2%_%Date:~3,2%_%Date:~6,4%_%Date:~0,2%_%Date:~3,2%_%Date:~6,2%
:: compress folder
7z a -tzip "%backup_dir%_%dt%.zip" "%db_dir%" -ssw
set backup_dir=C:\Users\FU386DKH\Desktop\ConsoleApplication2\
set db_dir=D:\Projects\NPCI\db\
:: set dt string in dd_mm_yy_HH_MM_SS format
set dt=%Date:~0,2%_%Date:~3,2%_%Date:~6,4%_%Date:~0,2%_%Date:~3,2%_%Date:~6,2%
:: compress folder
::Setting the path with the location of 7zip exe file.
set PATH=%PATH%;C:\Program Files\7-Zip\
7z a -tzip "%backup_dir%_%dt%.zip" "%db_dir%" -ssw

Azure App Service, run a native EXE to convert a file

I have a native EXE that converts a file based on command line arguments. Provided, I know how to give full path names of the input and output files, can I run such an EXE from my app service when some button is pressed and wait till the output file is created? Converting to DLL is not an option.
As far as I know, we could run a native exe in the azure app service.
But we couldn't directly pass the parameter to the native exe.
You need write a web application or something else for the user to type in the input parameter.
Then you could use Process.Start method to run the exe.
About how to do it , you could refer to this code sample.
I use ASP.NET MVC to get the input parameter then send the parameter to the exe and get the result.
public ActionResult Index()
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = Server.MapPath("/exe/Sum.exe"),
//Arguments could be replaced
Arguments = "1 2",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// do something with line
Response.Write( " The result is : " + line);
}
//await getResultAsync();
return View();
}
Result:

c# Open file on server using alternate credentials using default application

I routinely use Process.Start(file); to open a file (PDF, Work or Excel file typically) using the default application. However, in this case I need to open a file that is on a server and using different credentials. I've tried every variation of Process that I can think of and nothing seems to work.
string file = folderPath + dlg.listBox1.Items[dlg.listBox1.SelectedIndex].ToString();
Process.Start(file, "xxxx", GetSecureString("xx11xx"), "MyCompany.com");
with this I get "The directory name is invalid".
Process proc = new Process
{
EnableRaisingEvents = false,
StartInfo =
{
UseShellExecute = false,
Verb = "open",
UserName = "xxxx",
Password = GetSecureString("xx11xx"),
Domain = "MyCompany.com",
FileName = folderPath + dlg.listBox1.Items[dlg.listBox1.SelectedIndex].ToString(),
WorkingDirectory = folderPath,
Arguments = dlg.listBox1.Items[dlg.listBox1.SelectedIndex].ToString(),
}
};
proc.Start();
With this, I get is "The specified executable is not a valid Win32 application."
If I drop the folderPath from FileName; i get "The system cannot file the file specified".
By the way, I am using a class I found on StackOverflow to successfully access the folder on the server and copy files to it and list the files in it.
Any help would be appreciated.
Thanks.

Batch Script for Team Foundation Server's Get method throws error when called via a program

I use a batch script to automatically get and compile several solutions. Here is a sample snippet from the batch file:
"C:\...\IDE\TF.exe" get $/NG3rdParty/Main /recursive
This works fine when I call it from command prompt. However, I am writing a C# program to change the version numbers of DLLs, it does the following:
var businessFile= #"C:\Build\Common.AssemblyInfo.cs";
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(#"http://tfs:8080"));
var workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(businessFile);
var workspace = workspaceInfo.GetWorkspace(tfs);
workspace.PendEdit(businessFile);
var batchFilePath = #"\CleanBuild.bat";
var batchFile = path + batchFilePath;
var p = new Process
{
StartInfo =
{
FileName = batchFile,
UseShellExecute = true
}
};
p.Start();
p.WaitForExit();
When the batch file is called from program, the same line throws this exception:
Unable to determine the workspace. You may be able to correct this by running 'tf workspaces /collection:TeamProjectCollectionUrl'.
The BATCH script has no way of knowing anything about workspaces you have declared in your C# code. If you start the Process in the local workspace directory, it should work:
var p = new Process
{
StartInfo =
{
FileName = batchFile,
WorkingDirectory = "<local workspace dir>",
UseShellExecute = true
}
};
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx

Categories