C# Currency Persistence Class Implementation
Classified in Computers
Written on in
English with a size of 3.25 KB
Namespace Pers
{
public class Persistencia
{
Method: Add Currency (AniadirDivisa)
Adds a currency and its value to Divisas.txt if it does not already exist.
public static void AniadirDivisa(String d, double valor)
{
if (!ExisteDivisa(d))
{
StreamWriter sw = new StreamWriter(@"Divisas.txt", true);
sw.WriteLine(d + "\t" + valor);
sw.Close();
}
}Method: Get Currency Value (ValorDivisa)
Retrieves the value associated with a specific currency symbol.
public static double ValorDivisa(String d)
{
String v = "";
StreamReader sr = new StreamReader(@"Divisas.txt");
String l = sr.ReadLine();
while (l != null)
{
if (l.Contains(d))
{
// Extracts the value after the tab separator
v = l.Substring(l.IndexOf("\t") + 1);
}
l = sr.ReadLine();
}
sr.Close();
return Convert.ToDouble(v);
}Method: Delete Currency (eliminar)
Removes a specified currency entry by copying all other lines to a temporary file, deleting the original, and renaming the temporary file.
public static void Eliminar(String d)
{
StreamReader sr = new StreamReader(@"Divisas.txt");
// Note: Appending (true) is used here, but logic implies overwriting content if not careful.
StreamWriter sw = new StreamWriter(@"Divisas2.txt", false);
String l = sr.ReadLine();
while (l != null)
{
if (!l.Contains(d))
{
// Correction: Should write the entire line 'l', not just 'd'
sw.WriteLine(l);
}
l = sr.ReadLine();
}
sw.Close();
sr.Close();
System.IO.File.Delete(@"Divisas.txt");
File.Move(@"Divisas2.txt", @"Divisas.txt"); // Using Move is cleaner than Copy + Delete
}Method: Check Existence (ExisteDivisa)
Checks if a currency symbol exists in the file.
public static Boolean ExisteDivisa(String d)
{
Boolean existe = false;
StreamReader sr = new StreamReader(@"Divisas.txt");
String l = sr.ReadLine();
while (l != null)
{
if (l.Contains(d))
{
existe = true;
}
l = sr.ReadLine();
}
sr.Close();
return existe;
}Method: List All Currencies (ListarDivisas)
Returns a list of all currency symbols stored in the file.
public static List<String> ListarDivisas()
{
List<String> ls = new List<String>();
StreamReader sr = new StreamReader(@"Divisas.txt");
String l = sr.ReadLine();
while (l != null)
{
// Extracts the currency symbol before the tab separator
ls.Add(l.Substring(0, l.IndexOf("\t")));
l = sr.ReadLine();
}
sr.Close();
return ls;
}
}