16

I am trying to add a specific line of text in a file. Specifically between two boundaries.

An example of what it would look like if I wanted to add a line in between the boundaries of item1:

[item1]
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
//Add a line here in between the specific boundaries
[/item1]
[item2]
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 8
2550 coins 995 200000 7
2550 coins 995 200000 7
[/item2]
[item3]
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
2550 coins 995 200000 7
[/item3]

This is what I have tried so far, however Its nowhere near correct. It keeps saying that the file is being used by the reader so it cant be edited by the writer, when I did get it to work it cleared the entire document.

public void createEntry(String npcName)
{
    String line;
    String fileName = "Drops.de";
    StreamWriter streamWriter = new StreamWriter(fileName);
    StreamReader streamReader = new StreamReader(fileName);
    line = streamReader.ReadLine();
    if (line == ("[" + npcName + "]"))
    {
        streamReader.ReadLine();
        streamWriter.WriteLine("Test");
    }
}

I would also like to know how to write lines at the end of the document.

Hjalmar Z
  • 1,591
  • 1
  • 18
  • 36
Simon Taylor
  • 503
  • 2
  • 7
  • 17

3 Answers3

22

This will add the line where you want it. (Make sure you have using System.IO; and using System.Linq; added)

public void CreateEntry(string npcName) //npcName = "item1"
{
    var fileName = "test.txt";
    var endTag = String.Format("[/{0}]", npcName);
    var lineToAdd = "//Add a line here in between the specific boundaries";

    var txtLines = File.ReadAllLines(fileName).ToList();   //Fill a list with the lines from the txt file.
    txtLines.Insert(txtLines.IndexOf(endTag), lineToAdd);  //Insert the line you want to add last under the tag 'item1'.
    File.WriteAllLines(fileName, txtLines);                //Add the lines including the new one.
}
Hjalmar Z
  • 1,591
  • 1
  • 18
  • 36
  • Thanks for this, the only problem is that it keeps telling me that the file is in use, at "using (File.Create(fileName)){}" – Simon Taylor Apr 25 '13 at 11:56
  • Strange, it works fine for me. Do you have any other code that uses the file? You don't need any `FileStream`, `StreamWriter` or `StreamReader` for this to work. – Hjalmar Z Apr 25 '13 at 12:00
  • Ah, sorry. One of my other methods were influencing your one. Anyway it seems to be working great at the moment, Thanks :) – Simon Taylor Apr 25 '13 at 12:15
  • Glad you got it working. I hope this also covers your second question, you can use this code to add a line at the end as well. – Hjalmar Z Apr 25 '13 at 18:38
  • 1
    I don't suggest using that code to append text to the end. Because it has to totally load the entire file in memory. Instead, I suggest: using var fileSteam = File.AppendText(path); .fileSteam.WriteLine(newItem); – Anduin Xue Nov 17 '20 at 17:33
2

You should not open your file twice, try this:

FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamWriter streamWriter = new StreamWriter(fileStream);
StreamReader streamReader = new StreamReader(fileStream);

another think is logic for inserting line, maybe easier way is to copy data line by line into new file, insert new part when needed and continue. Or do it in memory.

To add line to the end you can use FileMode.Append or do your own seek

Viliam
  • 636
  • 9
  • 17
0

try this method

using System.IO;
using System.Linq;

    /// <summary>
    /// Add a new line at a specific position in a simple file        
    /// </summary>
    /// <param name="fileName">Complete file path</param>
    /// <param name="lineToSearch">Line to search in the file (first occurrence)</param>
    /// <param name="lineToAdd">Line to be added</param>
    /// <param name="aboveBelow">insert above(false) or below(true) of the search line. Default: above </param>
    internal static void insertLineToSimpleFile(string fileName, string lineToSearch, string lineToAdd, bool aboveBelow = false)
    {          
        var txtLines = File.ReadAllLines(fileName).ToList();
        int index = aboveBelow?txtLines.IndexOf(lineToSearch)+1: txtLines.IndexOf(lineToSearch);
        if (index > 0)
        {
            txtLines.Insert(index, lineToAdd);
            File.WriteAllLines(fileName, txtLines);
        }
    }
Xtian11
  • 2,130
  • 1
  • 21
  • 13