none
Adding a line in a text file in a certain place RRS feed

  • Question

  • ok i have a text file for example 

    public void replaceinside()
    {
    hello world
    }

    and i want the program to... to look though.. text file and find 

    public void replaceinside()

    then 

    {

    and add text inside the 

    {

    text added in here... 

    }

    i have come up with this but it wont add it in 

            public void addin()
            {
                string[] strArray = (string[])null;
                try
                {
                    strArray = File.ReadAllLines(path);
                }
                catch (Exception ex)
                {
                    int num = (int)MessageBox.Show(ex.Message);
                }
                if (strArray == null)
                    return;
                using (StreamReader streamReader = new StreamReader(path))
                {
                    string end = streamReader.ReadToEnd();
                    if (end.Contains("Hello World"))
                    {
    
                    }
                    if (!end.Contains("Hello World"))
                    {
                        streamReader.Dispose();
                        if (File.Exists(path))
                        {
                            string str = "Hello Wold";
                            string path1 = path;
                            List<string> stringList = new List<string>((IEnumerable<string>)File.ReadAllLines(path1));
                            int index = stringList.FindIndex((Predicate<string>)(item => item.Contains("Public void helpmeplease() {")));
                            if (index != -1)
                                stringList.Insert(index + 1, str);
                            File.WriteAllLines(path, (IEnumerable<string>)stringList);
                        }
                    }
                }
            }

    but it wont add it in any suggestions would be appreciated. 

    elfenliedtopfan5

    Saturday, December 2, 2017 6:21 PM

All replies

  • Maybe it is easier to find “hello world”, or to rewrite the whole file with new contents?

    Saturday, December 2, 2017 8:16 PM
  • Whats the errormessage?
    Saturday, December 2, 2017 8:35 PM
  • Maybe it is easier to find “hello world”, or to rewrite the whole file with new contents?

         you see this is just a test to try and get it to place it in the right place as the real file i will be using is gsc code and its a large file so i need to find that certain line and i need it to find that as if say for the example hello world was not there and i wanted to place hello world there i cant place it anywhere in a gsc file as it will break the code. 
    Saturday, December 2, 2017 8:36 PM
  • You are reading the file with File.ReadAllLines but then you don't use strArray. There are many other things that are unnecessary. So here is a simple console program that should help you.

    string[] strArray = (string[])null;
    try
    {
        strArray = File.ReadAllLines(inputfile);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Open error: {0}", ex.Message);
        return;
    }
    foreach (string s in strArray)
    {
        Console.WriteLine(s.Replace(fromstr, tostr));
    }
    

    The Replace method does replace the string. 



    Sam Hobbs
    SimpleSamples.Info

    Saturday, December 2, 2017 9:20 PM
  • You are reading the file with File.ReadAllLines but then you don't use strArray. There are many other things that are unnecessary. So here is a simple console program that should help you.

    string[] strArray = (string[])null;
    try
    {
        strArray = File.ReadAllLines(inputfile);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Open error: {0}", ex.Message);
        return;
    }
    foreach (string s in strArray)
    {
        Console.WriteLine(s.Replace(fromstr, tostr));
    }

    The Replace method does replace the string. 



    Sam Hobbs
    SimpleSamples.Info

          Thank you :) but what if i need to find a part in the text file like 
          public void whateverfunction()
          {

           would like to add text here...

          }

          the gsc file has loads of diffent functions so is there a way to look for just the 
          public void whateverfuntion()
          { just look for this and if found add text inside the brackets ? 

    Sunday, December 3, 2017 12:20 AM
  •       Thank you :) but what if i need to find a part in the text file like 

          public void whateverfunction()
          {

           would like to add text here...

          }

          the gsc file has loads of diffent functions so is there a way to look for just the 
          public void whateverfuntion()
          { just look for this and if found add text inside the brackets ? 

    Only you can answer that. It depends on many things, such as:

    • Is it just one file?
    • How many occurrences are there in the file(s)?
    • How often? Is this just one time or will you need to do it again for future versions?
    • Is the data always in that exact format?
    • Will be there a problem if it misses one or more?
    • Will be there a problem if it makes the change when it should not be?

    All those considerations can influence how you do it. You should already know the answer to most of them. Do you know how to use "Find in Files" in Visual Studio? If it were me I would certainly do research using that. Have you searched the file(s) for the relevant function? You should be able to get answers to many of those questions in less time  than it took to ask the question.

    There are many ways to solve the problem depending on the things I described. You could use the String.IndexOf Method to search for just the function name and ignore all lines that do not contain the function name, then if it is in a line then do more processing of that line. You could search for lines that have just the exact text if every line is exactly the same. Since your data is in an array you could easily look at the next line to see if it has "{".



    Sam Hobbs
    SimpleSamples.Info


    Sunday, December 3, 2017 2:44 AM
  •       Thank you :) but what if i need to find a part in the text file like 

          public void whateverfunction()
          {

           would like to add text here...

          }

          the gsc file has loads of diffent functions so is there a way to look for just the 
          public void whateverfuntion()
          { just look for this and if found add text inside the brackets ? 

    Only you can answer that. It depends on many things, such as:

    • Is it just one file?
    • How many occurrences are there in the file(s)?
    • How often? Is this just one time or will you need to do it again for future versions?
    • Is the data always in that exact format?
    • Will be there a problem if it misses one or more?
    • Will be there a problem if it makes the change when it should not be?

    All those considerations can influence how you do it. You should already know the answer to most of them. Do you know how to use "Find in Files" in Visual Studio? If it were me I would certainly do research using that. Have you searched the file(s) for the relevant function? You should be able to get answers to many of those questions in less time  than it took to ask the question.

    There are many ways to solve the problem depending on the things I described. You could use the String.IndexOf Method to search for just the function name and ignore all lines that do not contain the function name, then if it is in a line then do more processing of that line. You could search for lines that have just the exact text if every line is exactly the same. Since your data is in an array you could easily look at the next line to see if it has "{".



    Sam Hobbs
    SimpleSamples.Info


         this is example of the file 
    example
    Sunday, December 3, 2017 7:49 PM
  • I see you deleted the link. The one I got in the email seems to be the incorrect one.


    Sam Hobbs
    SimpleSamples.Info

    Sunday, December 3, 2017 8:12 PM
  • Sunday, December 3, 2017 8:14 PM
  • Sorry, same thing.


    Sam Hobbs
    SimpleSamples.Info

    Sunday, December 3, 2017 10:39 PM
  • Sorry, same thing.


    Sam Hobbs
    SimpleSamples.Info

          im sorry about this ;( try this one i uploaded it to mega instead might work now new link
    Sunday, December 3, 2017 10:55 PM
  • did it work ? 
    Monday, December 4, 2017 3:54 PM
  • Hello elfenliedtopfan2,

    The file you provided has neat structure and it reduce the file parse difficulty.

    function main()
    
    function footsteps()
    
    function start_intro_screen_zm()

    You could parse the file line by line. When you meet the above structure you will know the function name and the next line is "{". If the function name is what you want, the code block of the current function will continue until read "}", and replace the new string value to old string array. Finally save the file.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 5, 2017 10:50 AM
    Moderator
  • Hi elfenliedtopfan2,

    The following thread provide an idea for your reference, please check Ante Meridian's reply.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/b034757e-538a-48bf-9dd2-6fa435cc9c3e/c-adding-text-at-a-certain-place-in-a-text-file?forum=csharpgeneral

    Best regards,

    Zhanglong Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, December 13, 2017 6:34 AM
    Moderator