Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi..


I created .cs file in my project through stream writer, now i want to compile that cs file..
by using stream reader i am trying to execute that code,but it displaying error that...


" Compiler Error Message: CS0116: A namespace cannot directly contain members such as fields or methods"
Posted

Try it:

C#
protected void btnexecute_Click(object sender, EventArgs e)
{
    string pathToCs = Server.MapPath("~/App_Code/Function/Functions/" +  
                                     txtfunmoduleName.Text + ".cs"));
    
    ExecuteCode(pathToCs);
}

private void ExecuteCode(string PathToCSFile)
{
    string CodeSource = System.IO.File.ReadAllText(PathToCSFile);
    string exePath = System.IO.Path.ChangeExtension(PathToCSFile, ".exe");
    string assemblypath = GenerateCSharpAssembly(CodeSource, exePath);
    if (System.IO.File.Exists(assemblypath))
    {
        
        ProcessStartInfo procInfo = new ProcessStartInfo();
        procInfo.UseShellExecute = false;
        procInfo.WindowStyle = ProcessWindowStyle.Normal;
        procInfo.CreateNoWindow = false;
        procInfo.FileName = assemblypath;
        procInfo.RedirectStandardOutput = true;
        try
	{
	    // Start the process with the info we specified.
	    // Call WaitForExit and then the using statement will close.
	    using (Process exeProcess = Process.Start(procInfo))
	    {
		exeProcess.WaitForExit();
                string msg = exeProcess.StandardOutput.ReadToEnd();
                Response.Write(msg);
	    }
	}
	catch
	{
	    // Log error.
	}
        
    }

}

private string GenerateCSharpAssembly(string CodeSource, string exePath)
{
   
    CSharpCodeProvider provider = new CSharpCodeProvider();

    // add compiler parameters
    CompilerParameters compilerParams = new CompilerParameters();
    compilerParams.CompilerOptions = "/target:exe /platform:x86 /optimize";
    compilerParams.GenerateExecutable = true;
    compilerParams.GenerateInMemory = false;

    compilerParams.OutputAssembly = exePath;
    compilerParams.IncludeDebugInformation = false;
    compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
    compilerParams.ReferencedAssemblies.Add("System.dll");
    // Invoke compilation.
    CompilerResults cr = provider.CompileAssemblyFromSource(compilerParams, CodeSource);

    if (cr.Errors.Count > 0)
    {
        // Display compilation errors.

        string message = "";
        foreach (CompilerError ce in cr.Errors)
        {
            message += ce.ToString();
        }
      Response.Write(message); 
     return "";
    }
    else
    {
        return exePath;
    }
}
 
Share this answer
 
v5
Comments
Divyay208 21-Feb-13 0:37am    
i want it in web applications...I had two buttons one button is for save the .cs code and other button is for compiling that code:

my code is:
protected void btncheckcode_Click(object sender, EventArgs e)
{


StreamWriter Sw1 = new StreamWriter(Server.MapPath("~\\App_Code\\Function\\Functions\\" + txtfunmoduleName.Text+".cs"));
// StreamWriter Sw1 = new StreamWriter(@"D:\DBDEV\WebSite\App_Code\Function\Functions\" + txtfunmoduleName.Text + ".cs");
Sw1.WriteLine(txtcode.Text);
Sw1.Close();
txtcode.Text = "";


}
protected void btnexecute_Click(object sender, EventArgs e)
{
StreamReader SR = new StreamReader(Server.MapPath("~\\App_Code\\Function\\Functions\\" + txtfunmoduleName.Text + ".cs"));
txtcode.Text = SR.ReadToEnd();
SR.Close();

}

...here am able to save the .cs file but not able to compile that code, i want it in web application
Kuthuparakkal 21-Feb-13 0:50am    
changed code see now!
Divyay208 22-Feb-13 0:20am    
Thank u.. but now i have other requirement i.e

Hi..

I have .cs file in my app_code folder i need to create methods in that .cs file through user inter face

Function Name:.....
SourceCode:
.....
......
.......

I have this requirement, after writing the source code for that function it must be stored in .cs file which is already existing
Kuthuparakkal 22-Feb-13 2:52am    
This is not the correct way of doing things if you are looking for dynamic methods.... There is a DynamicMethod class to create methods at runtime and execute it. You have the flexibility of executing such methods using Invoke.
Kuthuparakkal 22-Feb-13 2:53am    
posting new solution..
After deep diving into actual requirements I would like to advise you that the path you selected to achieve the requirement is not appropriate.

There are very much convenient and flexible ways of doing things in standard way using .Net. Please get yourself familiarized with DynamicMethods and Invoking those methods at runtime.

Please have a look the following MSDN link:
http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx[^]


The following link has much more details(ie existing hard coded method and how it can be converted to dynamic method. Have a look.

http://www.devsource.com/c/a/Languages/Programming-a-Dynamic-Method-in-C/[^]

Thanks,

Kuthuparakkal
 
Share this answer
 
v2
Comments
Divyay208 22-Feb-13 6:11am    
my requirement is any one can create methods by writing function name, and source code, all users may not be familiar with dynamic methods,so please let me know the easiest mechanisum to create methods from ui
Kuthuparakkal 22-Feb-13 9:26am    
Can you explain why do you stick to that approach ? what's the benefit ? what's the real aim ?
Divyay208 23-Feb-13 3:25am    
Becuase I am developing the application like se37 function creation part in sap,Same functionality i just wana develop in .net
Kuthuparakkal 24-Feb-13 1:10am    
Okay.... Please consider the following things to prevent you application crash.
1. Ensure the method name should not duplicate.
2. Compile the code and make sure that it's error free before adding to your .cs file.
Divyay208 19-Feb-14 23:59pm    
thank u kruthuparakkal...can u please tell me how to compile that code before saving it on .cs file..and can u please give some suggestion that am writing C# .net code in my own editor and now i want to compile that code before saving it into a .cs file... if that code doesn't have any errors then i want to save that code into a .cs file

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900