How to save generated exe in Run-Time Compilation - c#

I am trying to save to Desktop generated code by CSharpProvider to Desktop. How can I do that?
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
textBox2.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
textBox2.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
textBox2.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
textBox2.ForeColor = Color.Blue;
textBox2.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output);
}
I don't want to run it just save it.

I have solved it . Changed the out.exe to c:\out.exe.

Related

when i use the gsutil in c# (diagnostics.process, cmd), it's does not end

I want to automate using gsutil in c #.
I use the "gsutil cp" command . If the file is small , the copied successfully . However, the file size is more than 10MB, the command is not end . I 've waited a long time , the command does not end .
This is my code.
String currentUser = Environment.UserName;
if (File.Exists(#"C:\Users\" + currentUser + #"\" + botoFileName) == false)
{
log.Error("can't find the confileFileName (" + botoFileName + ")");
return false;
}
log.Info("==========================================================");
log.Info("fileKey = " + fileKey);
string resultPro = null;
string resultError = null;
System.Diagnostics.ProcessStartInfo proInfo = new System.Diagnostics.ProcessStartInfo();
System.Diagnostics.Process pro = new System.Diagnostics.Process();
proInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
proInfo.CreateNoWindow = true;
proInfo.UseShellExecute = false;
proInfo.RedirectStandardOutput = true;
proInfo.RedirectStandardInput = true;
proInfo.RedirectStandardError = true;
pro.StartInfo = proInfo;
pro.Start();
pro.StandardInput.Write("c:" + Environment.NewLine);
pro.StandardInput.Write(#"set BOTO_PATH=C:\Users\" + currentUser + #"\" + botoFileName + Environment.NewLine);
if (usingCloudSdk.Equals("true"))
{
//when using google sdk and python
pro.StandardInput.Write(#"gsutil cp " + fileKey + " " + gcsPath + Environment.NewLine);
}
else
{
//when using only gsutil and python
pro.StandardInput.Write(#"cd C:\gsutil\gsutil" + Environment.NewLine);
pro.StandardInput.Write(#"python gsutil -m cp " + fileKey + " " + gcsPath + Environment.NewLine);
}
pro.StandardInput.Close();
resultPro = pro.StandardOutput.ReadToEnd();
resultError = pro.StandardError.ReadToEnd();
pro.WaitForExit();
pro.Close();
log.Info(resultPro);
log.Info(resultError);
log.Info("==========================================================");
if (resultError.IndexOf("Exception") != -1 || resultError.IndexOf("Fail") != -1)
{
return false;
}
return true;
please help me.

Stop CodeDom generated executables being detected as a virus

So when i generate a C# program using CodeDom and scan it online it comes up as being a virus. How do I stop this?
This is the code i am using to generate it:
string Output = "Out.exe";
string[] fileArray = { "source.cs", "AssemblyInfo.cs" };
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
parameters.ReferencedAssemblies.Add("System.dll");
CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, fileArray);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
MessageBox.Show(
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine);
}
}
else
{
MessageBox.Show("Success!");
}
This is the code i'm using for the generated exe
using System;
using System.Text;
namespace Out
{
class Program
{
static void Main(string[] args)
{
System.Text.StringBuilder sbMessage = new System.Text.StringBuilder();
Console.WriteLine(sbMessage.Append("the result of adding (1+2) is " + (1 + 2).ToString()));
System.Console.ReadLine();
}
}
}
So when I scan the generated file, its getting detected as a virus as showen in the VirusTotal link https://www.virustotal.com/en/file/d19cb8ad9c9de9da50a29acab91b53d10327b3023aa1a32c367d17c0c50fd28c/analysis/1434772258/

C# pass path in argument

I'm starting cmd as a process in C# and I want to pass a file path in the argument. How to do it?
Process CommandStart = new Process();
CommandStart.StartInfo.UseShellExecute = true;
CommandStart.StartInfo.RedirectStandardOutput = false;
CommandStart.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
CommandStart.StartInfo.FileName = "cmd";
CommandStart.StartInfo.Arguments = "(here i want to put a file path to a executable) -arg bla -anotherArg blabla < (and here I want to put another file path)";
CommandStart.Start();
CommandStart.WaitForExit();
CommandStart.Close();
EDIT:
Process MySQLDump = new Process();
MySQLDump.StartInfo.UseShellExecute = true;
MySQLDump.StartInfo.RedirectStandardOutput = false;
MySQLDump.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
MySQLDump.StartInfo.FileName = "cmd";
MySQLDump.StartInfo.Arguments = "/c \"\"" + MySQLDumpExecutablePath + "\" -u " + SQLActions.MySQLUser + " -p" + SQLActions.MySQLPassword + " -h " + SQLActions.MySQLServer + " --port=" + SQLActions.MySQLPort + " " + SQLActions.MySQLDatabase + " \" > " + SQLActions.MySQLDatabase + "_date_" + date + ".sql";
MySQLDump.Start();
MySQLDump.WaitForExit();
MySQLDump.Close();
You need to put the file path in double quotes and use a verbatim string literal (#) as SLaks mentioned.
CommandStart.StartInfo.Arguments = #"""C:\MyPath\file.exe"" -arg bla -anotherArg";
Example with an OpenFileDialog
using(OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filePath = "\"" + ofd.FileName + "\"";
//..set up process..
CommandStart.StartInfo.Arguments = filePath + " -arg bla -anotherArg";
}
}
Update to comment
You can format your string using String.Format.
string finalPath = String.Format("\"{0}{1}_date_{2}.sql\"", AppDomain.CurrentDomain.BaseDirectory, SQLActions.MySQLDatabase, date);
Then pass finalPath into the arguments.

C# Adding values to pictureboxes

I just recently posted something earlier regarding a C# game project I am working on in Microsoft visual C# express and after trial and error the code that I have presented underneath will not work. Does anyone have any advice or help they could give me on how to get it to work? the part of the code with the brackets and asterisks and arrows is the error that will not work for me. (NOTE: I am making a Form on Microsoft Visual C# express.)
if (buttonFlag[0])
{
return;
}
if (accept)
{
return;
}
textBox2.Text = "";
textBox1.Text = "";
offerCounter++;
---> [[[ **pictureBox2.Image**]]]<--- = tempLabel = buttonList[0].ToString();
LostValues(tempLabel);
textBox1.Text = "-> you just opend " + tempLabel + "\n";
CallZero(tempLabel);
if (offerCounter == 20)
{
finalValue = GetFinalValue();
MessageBox.Show("You win " + finalValue.ToString());
textBox1.Text = "Game is over" + "\n";
textBox1.Text += "you won: " + finalValue.ToString();
label16.Content = "you won:";
label17.Content = finalValue.ToString();
label18.Text = "Game Over";
accept = true;
}
if (offerCounter <= 18)
{
if ((offerCounter % 3) == 0)
{
GenerateNewOffer();
textBox1.Text += "-> you have a new offer ";
MessageBox.Show("you recieved a new offer !");
textBox2.Text = newOffer.ToString();
}
else
{
offerRemainder = 3 - (offerCounter % 3);
textBox1.Text += "-> Open " + offerRemainder.ToString() + "more box(es) for new offer";
}
}
else
{
textBox2.Text = "";
}
The PictureBox.Image Property takes an Image instance. Read MSDN for both and code accordingly.

CodeDom.compiler memory

I am generating assembly on runtime . Problem is that i cant get rid-of it after i am done with it. I need to destroy this assambly what i have created
string _Errors = "";
object[] parms = null;
CodeDomProvider _CodeCompiler = CodeDomProvider.CreateProvider("CSharp"); //new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();
CompilerParameters _CompilerParameters = new CompilerParameters();
_CompilerParameters.GenerateExecutable = false;
_CompilerParameters.GenerateInMemory = true;
_CompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
_CompilerParameters.TreatWarningsAsErrors = false;
_CompilerParameters.CompilerOptions = "/optimize";
try
{
System.CodeDom.Compiler.CompilerResults _CompilerResults = null;
_CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, _SourceCode);
if (_CompilerResults.Errors.Count > 0)
{
_Errors = "";
foreach (System.CodeDom.Compiler.CompilerError CompErr in _CompilerResults.Errors)
{
_Errors += "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";\r\n\r\n";
}
return false;
}
else
{
_Errors = null;
} _CompilerResults.CompiledAssembly = null;
_CompilerResults = null;
_CompilerParameters = null;
_CodeCompiler.Dispose();
GC.Collect();}catch{}
I suppose by "get rid of it" you mean "unload". Unfortunatelly (or not so) once loaded into an AppDomain, assemblies cannot be unloaded. To circumvent this, you can generate (or load, for that matter) assembly in a separate AppDomain and then destroy it as needed.

Categories