1

I have a requirement, in it I have to do the following things:

  1. Generate code dynamically
  2. Write the code into an existing .cs file
  3. I have to add the code just before the last two braces of the class file.

For e.g. the class file is :

namespace Stackoverflow
{
    public class AskQuestion
    {
        public void Ask()
        {
        }

    //Add the generated code here.
    }
}

I tried following code : Created a class FindBraceLocation

namespace DBInfo.Class
{
    public class FindBraceLocation
    {
        private int _bracePositionInLine;
        private int _noOfBraceFound;
        private int _lineNoIndex;
        private readonly string[] _fs;

        public int LineNoIndex
        {
            get { return _lineNoIndex; }
            set { _lineNoIndex = value; }
        }

        public int BracePositionInLine
        {
            get { return _bracePositionInLine; }
            set { _bracePositionInLine = value; }
        }

        public int NoOfBraceFound
        {
            get { return _noOfBraceFound; }
            set { _noOfBraceFound = value; }
        }

        public FindBraceLocation(string[] allLines)
        {
            _bracePositionInLine = -1;
            _noOfBraceFound = 0;
            _lineNoIndex = 0;
            _fs = allLines;
        }

        public void SearchFileStringIndex()
        {
            int noOfLines = _fs.Length;
            string line;
            int lineCounter;
            int pos2 = -1;

            for (lineCounter = noOfLines - 1; lineCounter >= 0; lineCounter--)
            {
                line = _fs[lineCounter];
                if (line.Trim().Length == 0)
                {
                    continue;
                }
                pos2 = FindIndexOfBrace(line);
                if (pos2 != -1)
                    break;
            }

            _lineNoIndex = lineCounter;
            _bracePositionInLine = pos2;
        }

        public int FindIndexOfBrace(string line)
        {
            //int braceNo = _noOfBraceFound;

            for (int counter = line.Length - 1; counter >= 0; counter--)
            {
                if (line[counter] == '}' && (++_noOfBraceFound == 2))
                {
                    return counter;
                }
            }
            return -1;
        }
    }

}

And used the following method to write it into a file :

        protected void WriteToExistingGeneratedFile(string strInfo, string strPath)
        {
            string[] allLines = File.ReadAllLines(strPath);
            FindBraceLocation fp = new FindBraceLocation(allLines);
            fp.SearchFileStringIndex();
            string lineForInsertion = allLines[fp.LineNoIndex];
            string tempLine = lineForInsertion.Substring(0, fp.BracePositionInLine) + "\n" + strInfo + "\n" + lineForInsertion.Substring(fp.BracePositionInLine);
            allLines[fp.LineNoIndex] = tempLine;
            File.WriteAllLines(strPath, allLines);

        }
11
  • 3
    So what is your question? Do you want someone to do it for you?
    – user1735181
    Jan 31, 2013 at 19:28
  • Show your work. What have you tried already?
    – Sam Axe
    Jan 31, 2013 at 19:29
  • Did you make any effort to accompplish this or just decide to post the question on here?
    – Brian Var
    Jan 31, 2013 at 19:32
  • I did try...This is taking a lot of time to write, is there any other way to do this.
    – User M
    Jan 31, 2013 at 19:33
  • Sounds like a case for CodeDOM to me. Jan 31, 2013 at 19:34

2 Answers 2

8

Instead of modifying the existing file, dynamically generate a second file and use the partial keyword to add new members to the class.

Static file:

namespace Stackoverflow
{
    public partial class AskQuestion
    {
        public void Ask()
        {
        }
    }
}

Generated file:

namespace Stackoverflow
{
    partial class AskQuestion
    {
        // Dynamically generated methods and properties
    }
}
7
  • The need for this functionality is that we have couple of methods to be added into a file dynamically and we are not sure how many, It may scale upto even 30-35 methods...
    – User M
    Jan 31, 2013 at 19:38
  • 2
    This is, by far, a better way to do it
    – Alan
    Jan 31, 2013 at 19:40
  • @UserM: Then figure out what these 30-35 methods are and write all of them at the same time to the file. Repeatedly appending more methods to a file is not a good idea.
    – dtb
    Jan 31, 2013 at 19:40
  • @UserM I'd like to hear more about the motivation behind this requirement. It seems bizarre, I wonder if it could be achieved through inheritance or extension methods or some other means?
    – Alan
    Jan 31, 2013 at 19:41
  • I don't see how the number of "injected" methods matter.
    – steinar
    Jan 31, 2013 at 19:43
0

If you use a stream reader you can use the normal string functions on it. Something like this would work:

System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.cs");
string myString = myFile.ReadToEnd();

// This will error if there are not at least 2 parentheses.
string UpToLastParan = myString.Text.Substring(0, myString.LastIndexOf("}"));
int SecondToLast = UpToLastParan.LastIndexOf("}");
string UpToSecondToLastParan = myString.Substring(0, SecondToLast);
string CorrectedString = UpToSecondToLastParan + "Your Code Here" + myString.Substring(SecondToLast, myString.Length - SecondToLast);

// Write back to file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.