Writing source code to a file

Posted on 2005-04-07
Last Modified: 2010-04-16
How could I go about adding a method to a sourcecode file that already exists?  i.e. add a method to a class?
Question by:jayrod
    LVL 14

    Assisted Solution

    by:Thandava Vallepalli

    here is the link to conver code to c# code.

    using System;
    using System.Collections;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.IO;
    using System.Reflection;
    using Microsoft.CSharp;
    using Microsoft.VisualBasic;
    public class ParseExpr

     public static void Main()
       Console.WriteLine("Expression evaluation demo");
       Console.WriteLine("Type an arithmetic expression: ");
       string Expression = Console.ReadLine();
       Console.WriteLine("Your expression is evaluated as: ");

     private static float ProcessExpression(string Expression)
       VBCodeProvider VBcp = new VBCodeProvider();
       ICodeGenerator cg = VBcp.CreateGenerator();
       string AssemblySourceFile = "MyClass.vb";
       string AssemblyFile = "MyClass.dll";
       TextWriter tw;
       tw = new StreamWriter(new FileStream(AssemblySourceFile, FileMode.Create));
       GenerateEvalMethod(tw, Expression, cg);
       ICodeCompiler cc = VBcp.CreateCompiler();
       CompilerParameters cpar = new CompilerParameters();
       cpar.OutputAssembly = AssemblyFile;
       cpar.GenerateExecutable = false;
       cpar.GenerateInMemory = false;
       CompilerResults compRes;
       compRes = cc.CompileAssemblyFromFile(cpar, AssemblySourceFile);
       Assembly ass;
       ass = compRes.CompiledAssembly;
       Type ty = ass.GetType("MyNamespace.MyClass");
       MethodInfo mi = ty.GetMethod("MyMethod");
       float Result = ((float)(mi.Invoke(null, null)));
       return Result;

     private static void GenerateEvalMethod(TextWriter tw, string Expression, ICodeGenerator CodeGen)
       CodeNamespace ns = new CodeNamespace("MyNamespace");
       CodeTypeDeclaration ty = new CodeTypeDeclaration("MyClass");
       ty.IsClass = true;
       ty.TypeAttributes = TypeAttributes.Public;
       CodeMemberMethod mm = new CodeMemberMethod();
       mm.Comments.Add(new CodeCommentStatement(String.Format("Expression:{0}", Expression)));
       mm.Name = "MyMethod";
       mm.ReturnType = new CodeTypeReference("System.Single");
       mm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
       mm.Statements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(Expression)));
       CodeGen.GenerateCodeFromNamespace(ns, tw, null);

    LVL 2

    Expert Comment

    is this a class you wrote? is anything set to final? in otherwords you could write a class that implements the interface from that class and overload all the function calls and members then write in your own code to handle the situations to need to change. Just my $.02
    LVL 3

    Author Comment

    well i'm trying to write unitTests so that would get very messy after a while.
    LVL 2

    Expert Comment

    Sorry I misread your question , you have the sourcecode for the file? then what is the real question? and what does writing the unit testing matrix have to do with modifying the code in the module anyway? sorry its still a bit early in the day for me so I might be catching on slow.
    LVL 3

    Author Comment

    well.. I'm writing a .net add in that will create test methods for the user. I'm trying to be simple here but I want that the first time the user clicks the addin that the sourcefile and the test class are all generated. Now if the user is in the same file and on the same method I want to insert a new "method" into the already existing class. This is because i'm inserting stubs and not code. so I can't trample over the code that is already there.

    make sense now?

    I've got it figured out how to create the initial code, now i'm trying to figure out how to insert code. By looking at codedom so far it doesn't appear to have a code file read in that will let me mess around with th ecound under test
    LVL 14

    Accepted Solution

    You might want to have a look at the System.Emit namespace. With this namespace you can dynamicly generate classes,methods,object and everything else at runtime. It lets you manipulate .cs files very easy.

    More information about this can be found at:
    LVL 3

    Author Comment

    I found the answer. You have to use fileCodeModel in the visual studio object.

    Thanks all for the help

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    C# ConsolApp opens new window 16 43
    Delegate in C# 3 38 mvc C# 2 27
    WPF issue with Trigger 2 35
    Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now