Skip to content

Instantly share code, notes, and snippets.

@mareksip
Last active August 29, 2015 14:05
Show Gist options
  • Save mareksip/d17e40d2e6f5fb542c34 to your computer and use it in GitHub Desktop.
Save mareksip/d17e40d2e6f5fb542c34 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace AppendLinesToTxt
{
class Program
{
static void Main(string[] args)
{
loadToArray();
}
static void loadToArray()
{
String txt = @"C:\Users\marek\Downloads\stackoverflow\append-lines\file1.txt";
string[] lines = new string[]{};
lines = File.ReadAllLines(txt);
lines[Array.IndexOf(lines, "write1")] = "newline1\nnewline2" ;
File.WriteAllText(txt, String.Empty);
foreach (string str in lines)
{
File.AppendAllText(txt, str + Environment.NewLine);
}
}
static void loadToList()
{
List<string> lines = new List<string>();
String txt = @"C:\Users\marek\Downloads\stackoverflow\append-lines\file1.txt";
using (StreamReader sr = File.OpenText(txt))
{
lines.Clear();
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
lines.Add(s);
if (s == "write1")
{
lines.Add("added item 1");
}
}
}
File.WriteAllText(txt, String.Empty);
foreach (string str in lines)
{
File.AppendAllText(txt, str + Environment.NewLine);
}
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment