protected void button_Click(object sender, EventArgs e) { var Countriesinlibrary = FileOperation.ReadCountryfromdatabase(); int counter = 0; var Countrytoadd = new Country(this.Country.Text,this.Capital.Text,int.Parse(this.Population.Text)); foreach (var item in Countriesinlibrary) { if (Country.Text.ToLower()==item.Name.ToLower()) { counter++; } } if (FileOperation.Addcountrytodatabase(Countrytoadd)&&counter==0) { this.messageLabel.Text = "Successfully added country"; this.Country.Text = string.Empty; this.Capital.Text = string.Empty; this.Population.Text = string.Empty; counter = 0; } else { this.messageLabel.ForeColor = System.Drawing.Color.Red; this.messageLabel.Text = "An error occured while adding the country"; } }
public static bool Addcountrytodatabase(Country CountrytoAdd) { try { using (var writer = new StreamWriter(FileOperation.FilePath, true)) { writer.WriteLine(CountrytoAdd); } return true; } catch (Exception) { return false; } }
public static List<Country> ReadCountryfromdatabase() { var listOfCountries = new List<Country>(); using (var reader = new StreamReader(FileOperation.FilePath)) { var CurrentCountry = reader.ReadLine(); while (CurrentCountry != null) { var currentCountry = CurrentCountry.Split('|'); var Country = new Country( currentCountry[0].Trim(), currentCountry[1].Trim(), int.Parse(currentCountry[2].Trim())); listOfCountries.Add(Country); CurrentCountry = reader.ReadLine(); } } return listOfCountries; }