0

I know, I know, I probably confused you! :)

I have this:

namespace WebPageHeaderFixer
{
    class Program
    {
        static void Main(string[] args)
        {
            string folderToSearch = @"C:\Test\";

            foreach (string file in Directory.GetFiles(folderToSearch))
            {
                string fileString = File.ReadAllText(file);

                //Here, I want to insert string X into "fileString" AFTER string Y.
            }
        }
    }
}

I want to add the string X into the variable fileString after the LAST Register TagPrefix:

<%@ Register TagPrefix="ucCal" TagName="popupCalendar" Src="../UserControls/popupCalendar.ascx" %>
<%@ Register TagPrefix="ucRes" TagName="Search" Src="../UserControls/SearchControl.ascx" %>
<%@ Register TagPrefix="abc" TagName="header" Src="../Header.ascx" %>
//I want to insert X here
other code
some more code
some ugly code

How do I go about doing this?

*Please note that the last Register tag might be different between files.

1
  • Do any of your <%@ Register ... %> tags span multiple lines, or is each one contained to its own line? Commented Jul 13, 2013 at 0:37

2 Answers 2

1

Using insert method and indexof method and lastindexof method it can be done like this:

int LastRegister = fileString.LastIndexOf("Register TagPrefix");
int InsertPosition = fileString.IndexOf('>', LastRegister) + 2;
fileString = fileString.Insert(InsertPosition, "String x");

This sets the insert position 2 characters past the index of the '>' following the last occurrence of "Register TagPrefix", which should put the insert position at the start of the next line. If the string has 2 characters for end of line you may have to offset the insert position by one more.

Sign up to request clarification or add additional context in comments.

Comments

1

Can you read the file line by line instead of a single string? You could then cycle through the lines to find the last occurrence of the string you are interested in, then you can write the lines back to the file, inserting your string after it.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.