Reputation: 37
I wish to invoke code that is in selected txt file. It works fine until file content is something simple like "Text string". It also works if i pass string parameter into it. But when i try passing an object like in my case Global it fails. Error is: "The type or namespace name 'Global' could not be found (are you missing a using directive or an assembly reference?)" Here is some code..
private void button1_Click(object sender, EventArgs e)
{
Scripting scriptObj = new Scripting();
scriptObj.fileName = this.openFileDialog1.FileName;
scriptObj.tekst = File.ReadAllText(this.openFileDialog1.FileName);
string exit = scriptObj.GetAction();
this.label1.Text = exit;
}
namespace WindowsFormsApplication2
{
public class Global
{
public string fileName = "test string";
}
public class Scripting
{
public string tekst = "";
public string fileName = "";
public string MyMethod1(Global obj) { return (obj.fileName); }
public string GetAction()
{
string sourceCode = @" namespace WindowsFormsApplication2 { public class Scripting { public string MyMethod (Global obj) { return (" + tekst + "); }}}";
var compParms = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults = csProvider.CompileAssemblyFromSource(compParms, sourceCode);
if (compilerResults.Errors.HasErrors)
{
StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
foreach (CompilerError error in compilerResults.Errors)
{
errors.AppendFormat("Line {0},{1}\t: {2}\n",
error.Line, error.Column, error.ErrorText);
}
return errors.ToString();
}
else
{
Global newGlobal = new Global();
newGlobal.fileName = "TEsTfileNameToOutput";
object typeInstance = compilerResults.CompiledAssembly.CreateInstance("WindowsFormsApplication2.Scripting");
MethodInfo mi = typeInstance.GetType().GetMethod("MyMethod");
string methodOutput = (string)mi.Invoke(typeInstance, new object[]{ newGlobal });
return methodOutput;
}
}
}
}
Why does
public string MyMethod (Global obj) { return (" + tekst + "); }
not take Global as param, but it works ok with MyMethod1
public string MyMethod1(Global obj) { return (obj.fileName); }
Content of selected file is: obj.fileName
Upvotes: 1
Views: 163
Reputation: 1500485
You haven't included a reference to the current assembly, which is the assembly declaring Global
. Therefore the compiler has no idea which type you're talking about.
You need to set the ReferencedAssemblies
property in the CompilerParameters
that you're creating.
Upvotes: 3