Skip to content

Instantly share code, notes, and snippets.

@d630
Last active July 4, 2018 23:03
Show Gist options
  • Save d630/4ab20a828c6e5e5a45fe89f66b93fa02 to your computer and use it in GitHub Desktop.
Save d630/4ab20a828c6e5e5a45fe89f66b93fa02 to your computer and use it in GitHub Desktop.
Tag 16: r/w
using System;
using System.Collections.Generic;
using System.IO;
namespace person
{
class Person
{
public Person(string nachname, string vorname)
{
this.Vorname = vorname;
this.Nachname = nachname;
}
public string Vorname { get; set; }
public string Nachname { get; set; }
public override string ToString()
{
return $"{Nachname}|{Vorname}";
}
}
class Personen
{
private List<Person> li = new List<Person>();
public Personen(string file, string mode)
{
switch (mode)
{
case "read":
readFile(file);
break;
case "write":
writeFile(file);
break;
case "append":
appendFile(file);
break;
default:
Console.WriteLine("Error: Unknown mode.");
break;
}
}
public void addPerson(string nachname, string vorname)
{
this.li.Add(new Person(nachname, vorname));
}
public void readFile(string file)
{
if (!File.Exists(file))
{
Console.WriteLine("Error: File can not be read.");
return;
}
FileStream fs = null;
StreamReader sr = null;
string[] field;
try
{
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
sr = new StreamReader(fs);
while (sr.Peek() != -1)
{
field = sr.ReadLine().Split('|');
this.li.Add(new Person(field[0], field[1]));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (sr != null)
sr.Close();
if (fs != null)
fs.Close();
}
}
public void writeFile(string file)
{
if (this.li.Count == 0)
{
Console.WriteLine("Error: Empty list.");
return;
}
FileStream fs = null;
StreamWriter sw = null;
try
{
fs = new FileStream(file, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs);
foreach (var p in this.li)
sw.WriteLine(p.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (sw != null)
sw.Close();
if (fs != null)
fs.Close();
}
}
public void appendFile(string file)
{
if (this.li.Count == 0)
{
Console.WriteLine("Error: Empty list.");
return;
}
FileStream fs = null;
StreamWriter sw = null;
try
{
fs = new FileStream(file, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
foreach (var p in this.li)
sw.WriteLine(p.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (sw != null)
sw.Close();
if (fs != null)
fs.Close();
}
}
}
class Program
{
static void Main(string[] args)
{
var f = File.Create("/tmp/foo.txt");
f.Close();
var p = new Personen("/tmp/foo.txt", "read");
p.addPerson("mustermann", "max");
p.addPerson("d", "john");
p.writeFile("/tmp/foo.txt");
p.addPerson("gandhi", "mahatma");
p.appendFile("/tmp/foo.txt");
string[] lines = File.ReadAllLines("/tmp/foo.txt");
foreach (var s in lines)
Console.WriteLine(s);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment