Click here to Skip to main content
15,994,549 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I've been trying to write new texts in a specific line without completely overwriting the current contents of the file but I can't seem to make it work. For example, in my file called Test.txt, This is whats currently written in it:

1
2
3
4

8
9
10

As you may have noticed, I did not inlude the numbers 5,6 and 7. There is also a space where you can insert 5,6 and 7. But as i tried inserting those numbers, its giving me this output:

1
2
3
4

8
9
101
2
3
4

5
6
7

It clearly have added a bunch of numbers that I did not want. Code for this is indicated below. Hope you guys can help me on this one.

What I have tried:

C#
namespace TestCode
{
    class Program2
    {
        static void Main()
        {

            var lines = System.IO.File.ReadAllLines(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt");
            lines[5] = "5";
            lines[6] = "6";
            lines[7] = "7";
            System.IO.File.AppendAllLines(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\Test.txt", lines);

            

        }
    }
}
Posted
Updated 26-Jan-17 11:53am
Comments
[no name] 26-Jan-17 8:08am    
"AppendAllLines", what exactly do you think "append" means?

Your problem is AppendAllLines. That method adds whatever you are writing to the end of the file. Use WriteAllLines instead.

Also, your insertion of lines is a replacement. There are a few ways of fixing that. You can
1. Use a list instead of an array, and Insert the lines in the appropriate place.
2. Create a new array with the correct number of rows, and copy the read values into the right places.
3. Set lines[4] = "5" + Environment.NewLine + "6" + Environment.NewLine + "7" + Environment.NewLine

**Note - the indexes of the lines need to be zero based, so they are 1 less than the number you have in the line.
 
Share this answer
 
v2
Comments
Afzaal Ahmad Zeeshan 26-Jan-17 8:30am    
5ed.

As for the option 1, he can also add the elements to any place and then finally just sort the array. Insertion of each element will take same amount of time.
[no name] 27-Jan-17 8:44am    
giving an actual example is much better for me to understand. Sorry im still a beginner in coding.
As already mentioned by NotPoliticallyCorrect in the comment to your question, the AppendAllLines will only append the list to your current data. Nothing more, nothing less.

In order to add 5,6,7 (to the current data and only applicable to this scenario), you also need to later sort the data. That sorting of the data will arrange the lines accordingly.
C#
// read the data
var lines = File.ReadAllLines("path");
var _lines = new List<string>(lines); // string[] to List<string>

_lines.Add("5");
_lines.Add("6");
_lines.Add("7");
lines = _lines.ToArray(); // Come back.

// sort
Array.Sort(lines);

// Write the data
File.WriteAllLines("path", lines);

That will write the data in sequence. You can consider using LINQ here as well, that will give a better readability for the code, but that would require a bit more tinkering to get the code to work.

One more thing, since the data is of string type, the sorting will be like, "1, 10, 2..." and not like, "1, 2,... 10", to use the later one you need to cast the data to integer and then sort it. For that you should look at, Convert.ToInt32() method and use that to convert the list to integers before sorting it.

For an example, please have a look here, Home | .NET Fiddle[^]
 
Share this answer
 
v2
Comments
[no name] 27-Jan-17 8:42am    
the code works fine but what if i dont want to sort it?. Because honestly i just used numbers as an example and im really not going to sort numbers. My main objective is to insert the numbers 5, 6 and 7 right through the space that was indicated in my post above without overwriting 8,9,10. I've tried removing the sort part of the code but it overwrites the 8,9 and 10.
Afzaal Ahmad Zeeshan 27-Jan-17 8:56am    
Then, you will need to pass the index and then use _list.Insert(6, "5") instead of the Add function. That will give you the ability to add a specific index, and the rest of the code remains as it is.

The benefit to use List over the static array, is that to update, or modify the array, such as in the cases of addition of or removal of the elements needs a lot of good logic to add the elements or remove a node. In list, that is managed automatically internally.

Read more on List.Insert here.
[no name] 27-Jan-17 9:19am    
Its working now. Thank you so much!
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. It allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
Comments
[no name] 27-Jan-17 8:45am    
thanks for the advice.

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