How to fix ''System.ArgumentException" in c#? - c#

I'm working on a small project that involves compiling code. I keep getting this error: An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll Illegal characters in path.
I've tried finding the source of the problem, this line of code seems to be the problem: CompilerResults cr = provider.CompileAssemblyFromFile(parameters, source1);
This is my code for my class:
using System.IO;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace Plugin___Prototype
{
class CompileCode
{
public void Compile()
{
string source1 = File.ReadAllText(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\test.cs");
//string source2 = File.ReadAllText(#"Source path here");
Console.WriteLine(source1);
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("System.dll");
parameters.GenerateExecutable = true;
parameters.OutputAssembly = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\app1.exe";
Console.WriteLine(parameters.OutputAssembly);
parameters.GenerateInMemory = false;
CompilerResults cr = provider.CompileAssemblyFromFile(parameters, source1);
if (cr.Errors.Count == 0)
Console.WriteLine("No Errors");
else
{
foreach (CompilerError error in cr.Errors)
Console.WriteLine(error.ErrorText);
}
Console.ReadLine();
}
}
}
This is the output:
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Illegal characters in path.
The program '[14128] Plugin - Prototype.exe' has exited with code -1 (0xffffffff).
My expected result is for app1.exe to generated in my documents folder.
EDIT: These are the contents of source1:
// A Hello World! program in C#.
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}

I've fixed it, CompilerResults cr = provider.CompileAssemblyFromFile(parameters, source1);, wanted the file not the contents of the file.

Related

When I open my compiled file it does nothing

I made a simple compiler to learn about CodeDom. But it does not work, when I try to open my compiled file it does nothing.
When I run the code and slect an dir to save the exe file the exe file is generated, but when I click the exe file it does nothing.
The builder:
using System;
using System.IO;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Windows.Forms;
namespace TestBuilder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void build(string output, string title, string msg)
{
CompilerParameters p = new CompilerParameters();
p.GenerateExecutable = true;
p.ReferencedAssemblies.AddRange(new String[] { "System.dll"});
p.OutputAssembly = output;
p.CompilerOptions = "/t:winexe";
string source = File.ReadAllText(#"C:\Users\Gebruiker\Documents\visual studio 2015\Projects\TestCompiler\Test\Program.cs");
string errors = String.Empty;
source = source.Replace("[MESSAGE]", msg);
CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(p, source);
if (results.Errors.Count > 0)
{
foreach (CompilerError err in results.Errors)
{
errors += "Error: " + err.ToString() + "\r\n\r\n";
}
}
else errors = "Successfully built:\n" + output;
MessageBox.Show(errors, "Build", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "EXE files (*.exe)|*.exe";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.OK)
{
build(sfd.FileName, textBox1.Text, textBox1.Text);
}
}
}
}
The program.cs file:
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("[MESSAGE]");
Console.ReadLine();
}
}
}
How can I fix this problem, so when I compile a file and execute it, it shows the message I put in the textbox?
Change p.CompilerOptions = "/t:winexe"; to p.CompilerOptions = "/t:exe";.
After that the compiled program should output whatever you've put inside your TextBox when you run it.
Source
Use /target:exe to create a console application.

XamlReader.Load is throwing System.Windows.Markup.XamlParseException

What could be wrong with the following:
<Run FontWeight=\"Bold\" Foreground=\"#FF0000FF\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xml:space=\"preserve\"><Run.TextDecorations><TextDecoration Location=\"Underline\" /></Run.TextDecorations>046/98 5802007513 \r</Run>
While similar others are loaded fine by the XamlReader.Load, this throws following exception:
"A first chance exception of type
'System.Windows.Markup.XamlParseException' occurred in
PresentationFramework.dll
Additional information: Invalid character in the given encoding. Line
1, position 233."
Code to replicate the issue:
using System;
using System.IO;
using System.Text;
using System.Windows.Markup;
namespace XamlTesting
{
class Program
{
static void Main(string[] args)
{
String str = "<Run FontWeight=\"Bold\" Foreground=\"#FF0000FF\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xml:space=\"preserve\"><Run.TextDecorations><TextDecoration Location=\"Underline\" /></Run.TextDecorations>046/98 5802007513 \r</Run>";
Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(str));
try
{
var temp = XamlReader.Load(s);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
Calling XamlReader.Parse instead of XamlReader.Load doesn't throw exception "XamlParseException" with the same input, however I don't know what's the difference and how it is working.
static void Main(string[] args)
{
String str = "<Run FontWeight=\"Bold\" Foreground=\"#FF0000FF\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xml:space=\"preserve\"><Run.TextDecorations><TextDecoration Location=\"Underline\" /></Run.TextDecorations>046/98 5802007513 \r</Run>";
try
{
var temp = XamlReader.Parse(str);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
use " (Double quote) instead of \ as show below
String str = #"http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xml:space=""preserve"">046/98 5802007513 \r";

CodeDOM compiler error, no main entry point

I'm using the code:
SaveFileDialog sfd = new SaveFileDialog();
sfd.ShowDialog();
string source = Properties.Resources.source;
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = sfd.FileName + ".exe";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.CompilerOptions = "/target:winexe";
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
parameters.ReferencedAssemblies.Add("System.Management.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll");
parameters.ReferencedAssemblies.Add("System.DirectoryServices.AccountManagement.dll");
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, Properties.Resources.source);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
MessageBox.Show("Error on line #" + CompErr.Line + " " + CompErr.ErrorText);
}
}
else
{
MessageBox.Show("Successfully Compiled.");
}
To compile my source, which is:
using System; 
static void Main(string[] args)
{
}
I'm getting the error:
Error on line #0 Program 'c:\Users\Tom\Desktop\s.exe' does not contain a static 'Main' method suitable for an entry point
From Googling and looking here, I am unable to find why this is throwing an error..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
public static void Main(string[] args)
{
}
}
}
This is also not working, I'm getting the same error.

C# SVN Pre Commit Hook, SharpSvn error

I have a C# console application that I use as an SVN Pre Commit Hook. The console app is started perfectly. However, as soon as I try to do a Write using SharpSvn, I get this error:
Commit failed (details follow):
Commit blocked by pre-commit hook (exit code -1066598274) with output:
Unhandled Exception: System.Runtime.InteropServices.SEHException: External
component has thrown an exception.
at svn_client_cat2(svn_stream_t* , SByte* , svn_opt_revision_t* ,
svn_opt_revision_t* , svn_client_ctx_t* , apr_pool_t* )
at SharpSvn.SvnClient.Write(SvnTarget target, Stream output, SvnWriteArgs args)
at SharpSvn.SvnClient.Write(SvnTarget target, Stream output)
at SvnPreCommitHook.Program.Main(String[] args)
I have tried to do the svn.Write command from my own machine, pointing to svn://svn-server instead of localhost - and that works fine. I guess it is something on the server. TortoiseSVN is installed, although I don't see any context menus...
My code looks like this:
private static EventLog _serviceEventLog;
static void Main(string[] args)
{
_serviceEventLog = new EventLog();
if (!System.Diagnostics.EventLog.SourceExists("Svn Hooks"))
{
System.Diagnostics.EventLog.CreateEventSource("Svn Hooks", "Svn Hooks");
}
_serviceEventLog.Source = "Svn Hooks";
_serviceEventLog.Log = "Svn Hooks";
SvnHookArguments ha;
if (!SvnHookArguments.ParseHookArguments(args, SvnHookType.PreCommit, false, out ha))
{
/*Console.Error.WriteLine("Invalid arguments");
Environment.Exit(1);*/
}
using (SvnLookClient cl = new SvnLookClient())
{
SvnChangeInfoEventArgs ci;
cl.GetChangeInfo(ha.LookOrigin, out ci);
if (!ci.LogMessage.Equals("Svn Hook Test"))
{
AllowCommit();
return;
}
var checkoutDir = #"C:\SvnTemp\" + DateTime.Now.Ticks.ToString();
foreach (SvnChangeItem i in ci.ChangedPaths)
{
var checkoutFilepath = checkoutDir + "\\" + Path.GetFileName(i.Path);
if (!Directory.Exists(checkoutDir))
{
Directory.CreateDirectory(checkoutDir);
}
using (SvnClient svn = new SvnClient())
{
using (StreamWriter sw = new StreamWriter(checkoutFilepath))
{
svn.Write(SvnTarget.FromString("svn://localhost/" + i.RepositoryPath), sw.BaseStream);
}
}
var fileContents = File.ReadAllText(checkoutFilepath);
if (fileContents.Contains("Martin Normark"))
{
RemoveTempDirectory(checkoutDir);
PreventCommit("Name is not allowed!");
}
}
RemoveTempDirectory(checkoutDir);
}
AllowCommit();
}
Maybe one of the following:
64bit vs 32 bit
vcredist missing on the server
Maybe you should first catch the thrown exception by using the HandleProcessCorruptedStateExceptionsAttribute:
[HandleProcessCorruptedStateExceptions]
static void Main() // main entry point
{
try
{
}
catch (Exception ex)
{
// Handle Exception here ...
}
}

C# programmatically Compile Form at Runtime without console

Why compiling this create an exe which :
open a console
launch the form ?
What can be done for the runtime compiled form open alone, without console ?
//LIST OF USING
using System;
using System.Windows.Forms;
using System.CodeDom.Compiler;
//CODE TO COMPILE
string oSource = #"
using System.Windows.Forms;
using System;
namespace fTest
{
public static class Program
{
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
public class MyForm:Form
{
public MyForm()
{
this.Text=""Generated exe"";
MessageBox.Show(""Generated exe says H3110 W0r1d"");
}
}
}";
string compiledOutput="Generated.exe";
//COMPILATION WORK
String [] referenceAssemblies={"System.dll","System.Drawing.dll","System.Windows.Forms.dll"};
CodeDomProvider _CodeCompiler = CodeDomProvider.CreateProvider("CSharp");
System.CodeDom.Compiler.CompilerParameters _CompilerParameters =
new System.CodeDom.Compiler.CompilerParameters(referenceAssemblies,"");
_CompilerParameters.OutputAssembly = compiledOutput;
_CompilerParameters.GenerateExecutable = true;
_CompilerParameters.GenerateInMemory = false;
_CompilerParameters.WarningLevel = 3;
_CompilerParameters.TreatWarningsAsErrors = true;
_CompilerParameters.CompilerOptions = "/optimize /target:winexe";//!! HERE IS THE SOLUTION !!
string _Errors = null;
try
{
// Invoke compilation
CompilerResults _CompilerResults = null;
_CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, oSource);
if (_CompilerResults.Errors.Count > 0)
{
// Return compilation errors
_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";
}
}
}catch (Exception _Exception)
{
// Error occurred when trying to compile the code
_Errors = _Exception.Message;
}
//AFTER WORK
if (_Errors==null)
{
// lets run the program
MessageBox.Show(compiledOutput+" Compiled !");
System.Diagnostics.Process.Start(compiledOutput);
}else
{
MessageBox.Show("Error occurred during compilation : \r\n" + _Errors);
}
By default, csc compiles console applications. You need to add /target:winexe to compiler options.
have you tried adding "target:winexe" to the command line parameters?

Categories