Streamreader doesn't read data in text file C# - c#

I have two classes "allmethods.cs" and "caller.cs"
I have two methods in the "allmethods.cs" class which are "WritingMethod" and "ReadingMethod"
The program should write and read from a text file. It writes smoothly when I call the "WritingMethod" but When I call the "ReadingMethod" it shows null as if there is no data in the text file.
I can't identify the problem in my code, I'd be glad if anyone help me identify the problem.
Here is my code:
public class allmethods
{
private static string Name;
private static int ID;
private static int Age;
private static string Email;
private static string output;
public static void WritingMethod()
{
int count = 0;
while (count < 2)
{
Console.Write(" Enter your Name: ");
Name = Console.ReadLine();
Console.Write(" Enter your ID: ");
ID = int.Parse(Console.ReadLine());
Console.Write(" Enter your Age: ");
Age = int.Parse(Console.ReadLine());
Console.Write(" Enter your E-mail: ");
Email = Console.ReadLine();
StreamWriter Sw = new StreamWriter("fileone.txt", true);
string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
+ Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
Console.WriteLine(output);
Sw.WriteLine(output + Environment.NewLine);
Console.ReadLine();
Sw.Close();
count++;
}
}
public static void ReadingMethod()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = Sr.ReadLine();
Console.WriteLine("--Reading The File--" + Environment.NewLine + output + Environment.NewLine);
Console.ReadLine();
Sr.Close();
fsr.Close();
}
}
Thank you very much. Waiting for your answers.

It seems that you have not set the variable output. You have set line variable.
public static void ReadingMethod()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = Sr.ReadToEnd();
Console.WriteLine("--Reading The File--" + Environment.NewLine + line + Environment.NewLine);
Console.ReadLine();
Sr.Close();
fsr.Close();
}
What I have modified is changed from output to line.
Hope it helps.

This is the total solution for the series of your questions:
public partial class AllMethods {
static T ReadData<T>(String prompt, T value) {
Console.Write(prompt);
return (T)Convert.ChangeType(Console.ReadLine(), typeof(T));
}
public static void WritingMethod(int timesToInput) {
using(var sw=new StreamWriter(path, true))
for(var list=items.ToArray(); timesToInput-->0; ) {
var inputs=new Dictionary<String, object>();
for(var i=0; i<list.Length; ++i) {
var item=list[i];
var prompt=String.Format(" Enter your {0}: ", item.Key);
inputs.Add(
item.Key, AllMethods.ReadData(prompt, item.Value));
}
var output=String.Format(format, inputs.Values.ToArray());
sw.WriteLine(output+Environment.NewLine);
Console.WriteLine(output);
Console.ReadLine();
}
}
public static void ReadingMethod() {
var textFromFile=
String.Join(Environment.NewLine, File.ReadAllLines(path));
Console.WriteLine(
"--Reading The File--"+Environment.NewLine+textFromFile);
Console.ReadLine();
}
static AllMethods() {
items=new Dictionary<String, object>();
// add any item with name and type default value
items.Add("Name", default(String));
items.Add("ID", default(int));
items.Add("Age", default(int));
items.Add("Email", default(String));
var prompts=items.Select(
(item, index) => String.Format("{0}: {{{1}}}", item.Key, index));
format=
"Thank you for registration! Your Submitted information are: "
+Environment.NewLine
+String.Join(Environment.NewLine, prompts.ToArray());
path="fileone.txt";
}
static Dictionary<String, object> items;
static String format, path;
}
I'd suggest that to prepare for complete code, and don't ask duplicate questions.

Related

Passing string array's through methods in c#

I'm very new to C#
I'm trying to create code that takes input from a user and saves it in an array in the SignUp() method and then if I call the Profile() method it displays the personal information
The error that occurs is when I try and call the Profile() method in the main line it says "There is no argument given that corresponds to the required formal parameter 'privinfo' of Profile(string[])' "
using System;
namespace SDD_Assessment_2
{
class Program
{
static void Main(string[] args)
{
//SignUp();
var privInfo = SignUp();
Profile(privInfo);
}
static string[] SignUp()
{
string[] privinfo = new string[4];
Console.Write("First Name: ");
privinfo[0] = Console.ReadLine();
Console.Write("Last Name: ");
privinfo[1] = Console.ReadLine();
Console.Write("Email: ");
privinfo[2] = Console.ReadLine();
Console.Write("Password: ");
privinfo[3] = Console.ReadLine();
return privinfo;
}
static void Profile(string[] privinfo)
{
Console.WriteLine("Name: " + privinfo[0] + " " + privinfo[1]);
Console.WriteLine("Email: " + privinfo[2]);
Console.WriteLine("Password: " + privinfo[3]);
}
}
}
You're not saving the value returned from SignUp(), so when the method ends, the local data is deleted. You need to catch the value, and pass it to Profile method, which expects an array of strings as an input.
static void Main(string[] args)
{
var privInfo = SignUp();
Profile(privInfo);
...
}

Can't append a list to an existing file

I have an existing .txt file that I would like to use to store my data, but when using this code I get an error at line 39 at switch case 1.
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static List<Pw> Site = new List<Pw>();
static void Main(string[] args)
{
string file = #"C: \Users\james\Documents\DataFolder\Vault.txt";
string command = "";
while (command != "exit")
{
Console.Clear();
Console.WriteLine("Please enter a command: ");
command = Console.ReadLine().ToLower();
switch (command)
{
case "1":
AddPw();
File.AppendAllLines(file, Pw.Site);
break;
case "2":
if (File.Exists(file))
{
// Read all the content in one string
// and display the string
string str = File.ReadAllText(file);
Console.WriteLine(str);
}
break;
}
}
}
private static void AddPw()
{
Pw pw = new Pw();
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
Console.Write("Enter Your Password: ");
string password = Console.ReadLine();
pw.Password = password;
Site.Add(pw);
}
private static void PrintPw(Pw pw)
{
Console.WriteLine("Username/Email: " + pw.Username);
Console.WriteLine("Full Name: " + pw.FullName);
Console.WriteLine("Phone Number: " + pw.PhoneNumber);
Console.WriteLine("Password: " + pw.Password[0]);
Console.WriteLine("-------------------------------------------");
}
private static void ListPw()
{
if (Site.Count == 0)
{
Console.WriteLine("Your address book is empty. Press any key to continue.");
Console.ReadKey();
return;
}
Console.WriteLine("Here are the current people in your address book:\n");
foreach (var pw in Site)
{
PrintPw(pw);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
public class Pw
{
public string Username { get; set; }
public string FullName { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
}
I have updated your existing function.
using this function you can add and append data in existing file.
private static void AddPw(string filePath)
{
try
{
Pw pw = new Pw();
if (!File.Exists(filePath))
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
else
{
using (StreamWriter sw = File.AppendText(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
}
catch (Exception ex)
{
}
}
File.AppendAllLines(file, Pw.Site);
In this line, you need to pass an IEnumerable for AppendAllLines to work. You can easily convert Site (which is List<Pw>) to an IEnumerable<string> using the ConvertAll method. Here's one way of achieving this:
Replace that line with this:
File.AppendAllLines(file, Site.ConvertAll<string>(
(p) => string.Format("{0} | {1} | {2} | {3}\n",
p.Username,
p.FullName,
p.PhoneNumber,
p.Password
))
);
This "lambda" basically takes your Pw object and converts it into a string inline.

Copy Files and Folders Checking for existence

(Newer to C#)
I have an application that I have built that copies files and folders from one location to another. I originally had issues with folders. For some reason, it would try to copy the file over without creating the directory. I solved that by adding a second section to check if the folder exists and if not create it. I am sure there is a better way to handle this, but this is what worked, so I went with it. The ultimate goal is this.
check if the file/folder exists in the destination location and is older than the source file/folder
If the file/folder doesn't exist, copy it over. If the file/folder is older than the source, copy it over.
If the file folder exists in the destination and not in the source (indicating it was deleted) move the file from the destination location to an archive folder
Below is what I have so far, and it does everything but what is described in #3 above. Any ideas in regards to how I can add the ability from #3 into the functionality, or simplify the copy of files and create the folder if it doesn't exist would be much appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileCopy
{
class Program
{
public static string dtnow = DateTime.Now.ToString("mmdd_hhmm");
public static string watch_path = string.Empty;
public static string copy_path = string.Empty;
public static string final_copy_path = string.Empty;
public static string log_folder = #"C:\copylogs";
//public static string log_file = "copy_log";
public static string log_file = Path.Combine(log_folder + "\\copy_log" + dtnow + ".txt");
public static int newer_count = 0;
public static int skip_count = 0;
public static int copy_count = 0;
public static int totalcount = 0;
public static int currentcount = 0;
static void Main(string[] args)
{
if (args == null || args.Length < 2)
{
Console.WriteLine("Invalid Syntax");
return;
}
else
{
watch_path = args[0];
copy_path = args[1];
log_start_Check(log_folder,log_file);
CopyFolder(watch_path, copy_path);
finalcount_statement();
}
}
// Log Folder check and creation
public static void log_start_Check(string log_folder, string log_file)
{
Console.Write("Checking Log Folder: ");
if (!Directory.Exists(log_folder))
{
try
{
Directory.CreateDirectory(log_folder);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create Directory" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.Write("Checking Log File: ");
//Console.WriteLine(log_file);
if (!File.Exists(log_file))
{
try
{
File.Create(log_file);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create file" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.WriteLine();
}
// Copy Folder Functions
static public void CopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(destFolder))
Directory.CreateDirectory(destFolder);
totalcount = Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories).Count();
string[] files = Directory.GetFiles(sourceFolder);
totalcount = files.Length;
foreach (string file in files)
{
string name = Path.GetFileName(file);
FileInfo source_info = new FileInfo(file);
string dest = Path.Combine(destFolder, name);
FileInfo dest_info = new FileInfo(dest);
if (File.Exists(dest))
{
try
{
if (source_info.LastWriteTime > dest_info.LastWriteTime)
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
File.Copy(file, dest, true);
Console.Write("\rFile Newer, File Copied " + dest + " ");
Console.ResetColor();
newer_count++;
}
else
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("\r** - File Exists " + dest + " ");
Console.ResetColor();
skip_count++;
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
else
{
try
{
//Console.Write("\r"+currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
File.Copy(file, dest, false);
Console.Write("\rFile Copied " + dest + " ");
Console.ResetColor();
copy_count++;
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
currentcount++;
}
string[] folders = Directory.GetDirectories(sourceFolder);
foreach (string folder in folders)
{
string name = Path.GetFileName(folder);
string dest = Path.Combine(destFolder, name);
CopyFolder(folder, dest);
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, null, null);
}
}
// Error Handling to add messages to logs
public static void error_handling(string message, string fileident, string source)
{
using (System.IO.StreamWriter myFile = new System.IO.StreamWriter(log_file, true))
{
string finalMessage = string.Format("{0}: {1} SOURCE: {3} - DEST: {2}", DateTime.Now, message, fileident, source, Environment.NewLine);
myFile.WriteLine(finalMessage);
myFile.Close();
}
}
// Final Statement
public static void finalcount_statement()
{
Console.WriteLine("");
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("Total New Files Copied: " + copy_count);
Console.WriteLine("Total Newer Files Updated: " + newer_count);
Console.WriteLine("Total Files Skipped: " + skip_count);
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("");
Console.WriteLine("");
}
}
}
You can do it the same way around, maybe like this:
static public void ArchiveCopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(sourceFolder))
{
Directory.CreateDirectory(archivefolder + destFolder);
//Copy folder and files
}
}
}

C# How to read and add user input to a text file? [duplicate]

This question already has answers here:
Append lines to a file using a StreamWriter
(11 answers)
Open existing file, append a single line
(9 answers)
Closed 5 years ago.
I am trying to make a C# app that reads and outputs information from a .txt file and then allows the user to enter more information to the end of that file. I am trying to write the text file in CSV form, and I am having a lot of trouble figuring out how to add to the BOTTOM of the file. It seems that when I try, it overwrites the top line of the file. Any help is appreciated. Here is the code so far, sorry for any confusing lines-- I have been trying many different things i could find online to try to get it working.
class Program
{
static void Main(string[] args)
{
string UIName = "";
string UIInvoice = "";
string UIDue = "";
string UIAmount = "";
using (FileStream fs = new FileStream(#"C:\Accounts.txt", FileMode.Open))
using (StreamReader sr = new StreamReader(fs))
{
string content = sr.ReadToEnd();
string[] lines = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int lineCount = 0;
List<Account> accounts = new List<Account>();
foreach (string line in lines)
{
string[] column = line.Split(',');
if (lineCount != 0)
{
Account account = new Account();
account.AccountName = column[0];
account.InvoiceDate = column[1];
account.DueDate = column[2];
account.AmountDue = column[3];
accounts.Add(account);
}
lineCount++;
}
Console.WriteLine(content);
}
using (FileStream fs = new FileStream(#"C:\Accounts.txt", FileMode.OpenOrCreate))
using (StreamWriter sw = new StreamWriter(fs))
{
Account account = new Account();
account.AccountName = UIName;
account.InvoiceDate = UIInvoice;
account.DueDate = UIDue;
account.AmountDue = UIAmount;
//accounts.Add(account);
string fullText = (UIName + "," + UIInvoice + "," + UIDue + "," + UIAmount);
Console.WriteLine("Would you like to enter additional data?");
Console.WriteLine("Please enter the Account Name: ");
UIName = Console.ReadLine();
Console.WriteLine("Please enter the Invoice Date: ");
UIInvoice = Console.ReadLine();
Console.WriteLine("Please enter the Due Date: ");
UIDue = Console.ReadLine();
Console.WriteLine("Please enter the AmountDue: ");
UIAmount = Console.ReadLine();
File.AppendAllText("C:/Accounts.txt", fullText + Environment.NewLine);//can't get this way working, even after switching "\"s to "/"s. It says that the file is being used by another process.
Console.ReadLine();
}
}
}
}
Separate class:
public class Account
{
public string AccountName { get; set; }
public string InvoiceDate { get; set; }
public string DueDate { get; set; }
public string AmountDue { get; set; }
public static string GetAccountCSV(Account account)
{
string returnValue = account.AccountName + "," + account.InvoiceDate + "," + account.DueDate + "," + account.AmountDue;
return returnValue;
}
}
The .txt file says;
Account Name,Invoice Date,Due Date,Amount Due
Jane Doe,1/12/2017,2/12/2017,2000.00
Gonuts Inc,12/31/2017,2/28/2017,1566.50
You have multiple issues with the code.
You want to append the data to the end of the file but you are opening FileStream with OpenOrCreate mode. OpenOrCreate mode places file pointer at the start of the file. So after that whatever you write to the file it will overwrite the existing content of the file.
You are opening the FileStream and StreamWriter but do not use them to write contents to the file. Instead of File.AppendAllText You should use sw.WriteLine(fullText).
Also you are writing the file content at the wrong place in the code.
Following is the code with all the above problems removed.
static void Main(string[] args)
{
string UIName = "";
string UIInvoice = "";
string UIDue = "";
string UIAmount = "";
var filePath = #"D:\Accounts.txt";
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (StreamReader sr = new StreamReader(fs))
{
string content = sr.ReadToEnd();
string[] lines = content.Split(new string[] {Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries);
int lineCount = 0;
List<Account> accounts = new List<Account>();
foreach (string line in lines)
{
string[] column = line.Split(',');
if (lineCount != 0)
{
Account account = new Account();
account.AccountName = column[0];
account.InvoiceDate = column[1];
account.DueDate = column[2];
account.AmountDue = column[3];
accounts.Add(account);
}
lineCount++;
}
Console.WriteLine(content);
}
}
using (FileStream fs = new FileStream(filePath, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs))
{
Account account = new Account();
account.AccountName = UIName;
account.InvoiceDate = UIInvoice;
account.DueDate = UIDue;
account.AmountDue = UIAmount;
//accounts.Add(account);
Console.WriteLine("Would you like to enter additional data?");
Console.WriteLine("Please enter the Account Name: ");
UIName = Console.ReadLine();
Console.WriteLine("Please enter the Invoice Date: ");
UIInvoice = Console.ReadLine();
Console.WriteLine("Please enter the Due Date: ");
UIDue = Console.ReadLine();
Console.WriteLine("Please enter the AmountDue: ");
UIAmount = Console.ReadLine();
string fullText = (UIName + "," + UIInvoice + "," + UIDue + "," + UIAmount);
sw.WriteLine(fullText);
Console.ReadLine();
}
}
}
There are two issues with your code
You have to open file in append mode #ref chetan comment
You are creating fulltext string before reading from user input due to which its writing empty string to text file.
Please find working program class file below
class Program
{
static void Main(string[] args)
{
string UIName = "";
string UIInvoice = "";
string UIDue = "";
string UIAmount = "";
using (FileStream fs = new FileStream(#"C:/Accounts.txt", FileMode.Open))
using (StreamReader sr = new StreamReader(fs))
{
string content = sr.ReadToEnd();
string[] lines = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int lineCount = 0;
List<Account> accounts = new List<Account>();
foreach (string line in lines)
{
string[] column = line.Split(',');
if (lineCount != 0)
{
Account account = new Account();
account.AccountName = column[0];
account.InvoiceDate = column[1];
account.DueDate = column[2];
account.AmountDue = column[3];
accounts.Add(account);
}
lineCount++;
}
Console.WriteLine(content);
}
using (FileStream fs = new FileStream(#"C:/Accounts.txt", FileMode.Append))
using (StreamWriter sw = new StreamWriter(fs))
{
Account account = new Account();
account.AccountName = UIName;
account.InvoiceDate = UIInvoice;
account.DueDate = UIDue;
account.AmountDue = UIAmount;
//accounts.Add(account);
Console.WriteLine("Would you like to enter additional data?");
Console.WriteLine("Please enter the Account Name: ");
UIName = Console.ReadLine();
Console.WriteLine("Please enter the Invoice Date: ");
UIInvoice = Console.ReadLine();
Console.WriteLine("Please enter the Due Date: ");
UIDue = Console.ReadLine();
Console.WriteLine("Please enter the AmountDue: ");
UIAmount = Console.ReadLine();
string fullText = (UIName + "," + UIInvoice + "," + UIDue + "," + UIAmount);
File.AppendAllText("C:/Accounts.txt", fullText + Environment.NewLine);//can't get this way working, even after switching "\"s to "/"s. It says that the file is being used by another process.
Console.ReadLine();
}
}
}

Display multiple content to textbox depending on which option was selected from combobox

-- EDIT --
Worth to point out. While having a problem with different homework problem I see than I am able to use separate objects as an entry (which I probably should do). This would make working on my final problem much easier. This is a problem that might be usefull for me.
I am trying to display data to text box using foreach loop. The data should be displayed coresponding to the selection of combo box. For example if I want to display PC I should see only UserName and Password and if I add another entry for example WebSite I should see previous entry in it's format and new entry with fields URL, Username, and Password. I have tried IF-statement in my previous question but didn't seem to work properly.
StringBuilder sb = new StringBuilder();
foreach (AddEntry list in addedEntry)
{
sb.AppendLine();
sb.AppendLine("URL: " + list.URL);
sb.AppendLine("Software Name: " + list.SoftwareName);
sb.AppendLine("Serial Code: " + list.SerialCode);
sb.AppendLine("User Name: " + list.UserName);
sb.AppendLine("Password: " + list.Password);
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
Regards.
StringBuilder sb = new StringBuilder();
foreach (AddEntry list in addedEntry)
{
sb.AppendLine();
if (!string.IsNullOrEmpty(list.URL))
sb.AppendLine("URL: " + list.URL);
if (!string.IsNullOrEmpty(list.SoftwareName))
sb.AppendLine("Software Name: " + list.SoftwareName);
if (!string.IsNullOrEmpty(list.SerialCode))
sb.AppendLine("Serial Code: " + list.SerialCode);
if (!string.IsNullOrEmpty(list.UserName))
sb.AppendLine("User Name: " + list.UserName);
if (!string.IsNullOrEmpty(list.Password))
sb.AppendLine("Password: " + list.Password);
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
2nd Option
Add following method to AddEntry class
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
if (!string.IsNullOrEmpty(this.URL))
sb.AppendLine("URL: " + list.URL);
if (!string.IsNullOrEmpty(this.SoftwareName))
sb.AppendLine("Software Name: " + this.SoftwareName);
if (!string.IsNullOrEmpty(this.SerialCode))
sb.AppendLine("Serial Code: " + this.SerialCode);
if (!string.IsNullOrEmpty(this.UserName))
sb.AppendLine("User Name: " + this.UserName);
if (!string.IsNullOrEmpty(this.Password))
sb.AppendLine("Password: " + this.Password);
sb.AppendLine();
return sb.ToString();
}
then you can show all the added Entry as below
StringBuilder sb = new StringBuilder();
foreach (AddEntry entry in addedEntry)
{
sb.Append(entry.ToString());
}
mainWindow.ChangeTextBox = sb.ToString();
StringBuilder sb = new StringBuilder();
foreach (AddEntry list in addedEntry)
{
sb.AppendLine();
if (!string.IsNullOrEmpty(list.URL))
sb.AppendLine("URL: " + list.URL);
if (!string.IsNullOrEmpty(list.SoftwareName))
sb.AppendLine("Software Name: " + list.SoftwareName);
if (!string.IsNullOrEmpty(list.SerialCode))
sb.AppendLine("Serial Code: " + list.SerialCode);
if (!string.IsNullOrEmpty(list.UserName))
sb.AppendLine("User Name: " + list.UserName);
if (!string.IsNullOrEmpty(list.Password))
sb.AppendLine("Password: " + list.Password);
sb.AppendLine();
}
mainWindow.ChangeTextBox = sb.ToString();
Edit: I have used UnhandledException's version as it is much more legible than my solution was (and the conditional operator is generally frowned upon in most cases).
I also want to point out that your AddEntry class could be easier written using auto properties (assuming you're using .NET 3.0+).
See:
namespace Store_Passwords_and_Serial_Codes
{
class AddEntry
{
// Auto properties make this class a lot easier to read.
public string type { get; set; }
public string url { get; set; }
public string softwareName { get; set; }
public string serialCode { get; set; }
public string userName { get; set; }
public string password { get; set; }
// Non-default constructor.
public AddEntry(string type, string url, string softwareName, string serialCode, string userName, string password)
{
this.type = type;
this.url = url;
this.softwareName = softwareName;
this.serialCode = serialCode;
this.userName = userName;
this.password = password;
}
}
}
And lastly, as you have said, it's important that you don't save information for one entry type that would belong in another (for instance, you shouldn't save URL into a PC entry type, as it makes no sense to). This entire solution would probably be better off using stronger typed objects (i.e. WebPassword, PCPassword, SoftwareSerialCode, etc). These could all inherit from a base class (Entry or something to that effect) to make it easier to strongly type the list, as well.
For instance:
class Entry { }
class PCPassword : Entry
{
string userName { get; set; }
string password { get; set; }
public PCPassword(string uName, string pass)
{
this.userName = uName;
this.password = pass;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("User Name: " + this.userName);
sb.AppendLine("Password: " + this.password);
sb.AppendLine();
return sb.ToString();
}
}
You would then refer to it in your code as such:
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Making sure that type is selected.
if (cmbType.SelectedIndex != -1)
{
if (cmbType.SelectedIndex == 0)
{
if(textUserName.Text == String.Empty || textPassword.Text == String.Empty)
MessageBox.Show("Please fill all the fields!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
addedEntry.Add(new PCPassword(textUserName.Text, textPassword.Text));
MessageBox.Show("Entry was successfully added!", "Entry Added!", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearFields();
}
}
// etc, etc
// Print our items
StringBuilder sb = new StringBuilder();
foreach (Entry item in addedEntry)
{
sb.Append(item.ToString());
}
mainWindow.ChangeTextBox = sb.ToString();
}
}
Just thought I'd throw that out there ;)

Categories

Resources