Details entered in windows form will not save to CSV file - c#

the information I enter in my form is not being stored in my CSV file. Just a blank file. the file name updates with todays date.
here is my code.
private void btnSave_Click(object sender, EventArgs e)
{
string date = DateTime.Today.ToString("dd-MM-yyyy"); //get today's date
string filePath = "Policy_" + date + ".csv"; //create a name of the new csv file (including the date)
string delimiter = ","; //comma needed to create new csv file
StringBuilder sb = new StringBuilder();
foreach (DriverDetails driverDetails in driverDet) //go through the List called DriverDetails and examine each object in turn
{
sb.AppendLine(driverDetails.Title + delimiter + driverDetails.FName + delimiter + driverDetails.SName + delimiter + driverDetails.Dob + delimiter + driverDetails.Phone + delimiter + driverDetails.Email + delimiter + driverDetails.Employment + delimiter + driverDetails.Marital + delimiter + driverDetails.HouseNo + delimiter + driverDetails.Street + delimiter + driverDetails.Postcode + delimiter);//uild up a String containing all the data in the List
}
File.WriteAllText(filePath, sb.ToString());
//File.AppendAllText(filePath, sb.ToString()); //add the new string (made up of SEVERAL lines, each representing data from ONE order) to the end of the csv file
MessageBox.Show("Driver details saved to file");
}

I use the following code to fill the driverDet, and then can write the data to the csv file.
class DriverDetails
{
public string Title { get; set; }
public string FName { get; set; }
public string SName { get; set; }
}
List<DriverDetails> driverDet = new List<DriverDetails> {
new DriverDetails { Title = "T1", FName = "F1", SName = "S1"},
new DriverDetails { Title = "T2", FName = "F2", SName = "S2"},
new DriverDetails { Title = "T3", FName = "F3", SName = "S3"}};

You can replace
File.WriteAllText(filePath, csv.ToString());
with
File.AppendAllText(filePath, csv.ToString());

Related

Accessing List values when having few strings inside a value

So I have the following code:
void ReadFromCsv()
{
using (var reader = new StreamReader(#"d:\test.csv", Encoding.Default))
{
List<string> listA = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(values[0]);
}
Console.WriteLine(listA);
}
}
which is reading from my csv file and an example of a line I get is:
50,2,10,201,10,9090339,24-OCT-21 09.38.38.679000 AM,123456789,24/10/2021 09:39:23,22/10/2021 09:39:37,Sm123456789-SM-20211031-VSR-000123.pdf,,,,,26/01/2022 13:08:58,,2,,0
first of all, why are there many commas around the end of the line?
second of all, what if I wanted to access the value "10" (which is the 5th value ) of that string line, is that possible?,
or going further, my task is to check for that 5th value and if its 5 for example, I'd want to take every row with 5thvalue=5 and create a csv for them, if 5thvalue=10 I want to create a csv for those records, and so on. but one task at a time, how do I access that value?
1: commas around the end of the line mean first item of lines is empty ""
2: you can get 5th value as below:
string _list = "50,2,10,201,10,9090339,24-OCT-21 09.38.38.679000 AM,123456789,24/10/2021 09:39:23,22/10/2021 09:39:37,Sm123456789-SM-20211031-VSR-000123.pdf,,,,,26/01/2022 13:08:58,,2,,0";
var fiveIndex = _list.Split(',')[4];
3:
then you can get list of lines that have a value of fiveIndex
var result =_list.Split(',').Select((v, i) => new { value = v, index = i }).Where(item => item.value == fiveIndex);
In your example, line 3 and line 5 have a value of 10(index=2, index=4). Then you can save these lines in csv file.
ended up doing:
string chargeMonth = DateTime.Now.ToString("yyyyMM");
var fileCreationDate = DateTime.Now.ToString("yyyyMMdd");
string fileCreationTime = DateTime.Now.ToString("HHmmss");
string constVal = "MLL";
string fileType = "HIYUV-CHEVRA";
string[] values;
string header, sumRow;
string line, compId;
string inputFile = "records.CSV";
Dictionary<string, System.IO.StreamWriter> outputFiles = new Dictionary<string, System.IO.StreamWriter>();
using (System.IO.StreamReader file = new System.IO.StreamReader("D:\\" + inputFile, Encoding.Default))
{
header = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
values = line.Split(",".ToCharArray());
compId = values[3];
if (!outputFiles.ContainsKey(compId))
{
string outputFileName = constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV";
outputFiles.Add(compId, new System.IO.StreamWriter("D:\\" + outputFileName));
outputFiles[compId].WriteLine(header);
}
outputFiles[compId].WriteLine(line);
}
}
foreach (System.IO.StreamWriter outputFile in outputFiles.Values)
{
outputFile.Close();
}
and the mission is done.

Saving files to a folder with a numeric system C#

I am having some trouble with my program. Is there anyway to store an array to a file but every file have a different name. For Example:
1.txt
2.txt
3.txt
4.txt
I am using Visual Studio 2019 and Coding in C#. This is some of the code im using:
string selectedsite = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
string selectedsize = this.comboBox1.GetItemText(this.comboBox2.SelectedItem);
string selectedproduct = this.comboBox1.GetItemText(this.comboBox3.SelectedItem);
string selectedproxies = this.comboBox1.GetItemText(this.comboBox4.SelectedItem);
string selectedprofiles = this.comboBox1.GetItemText(this.comboBox5.SelectedItem);
string path = "d:\\bot\\bot\\Task.txt";
string[] FileInfo = { selectedsite," ", selectedsize, " ", selectedproduct, " ", selectedproxies, " ", selectedprofiles };
You can use File.WriteAllLines method to store an array to a file and every file have a different name.
Here is a code example you can refer to.
int count = 1;
string path =#"C:\Users\Desktop\Test\{0}.txt";
private void button2_Click(object sender, EventArgs e)
{
while (System.IO.File.Exists(string.Format(#"C:\Users\Desktop\Test\{0}.txt", count)))
{
count++;
}
string selectedsite = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
string selectedsize = this.comboBox1.GetItemText(this.comboBox2.SelectedItem);
string selectedproduct = this.comboBox1.GetItemText(this.comboBox3.SelectedItem);
string selectedproxies = this.comboBox1.GetItemText(this.comboBox4.SelectedItem);
string selectedprofiles = this.comboBox1.GetItemText(this.comboBox5.SelectedItem);
string[] FileInfo = { selectedsite, " ", selectedsize, " ", selectedproduct, " ", selectedproxies, " ", selectedprofiles };
var newFileName = string.Format(#"C:\Users\Desktop\Test\{0}.txt", count);
count++;
System.IO.File.WriteAllLines(newFileName, FileInfo);
}

I cannot figure out how to fix an unhandled Format Excpetion

I am trying to write a C# program using Visual Studio that reads data from a file and allow me perform various sorts on the data. I am a beginner so it took much research to figure out how to write this code: Now I get a:
Format Exception was unhandled. Input string was not in a correct
format
I am not sure where I went wrong. This is happening for the following line of code:
Candidate newrec = new Candidate(str[0], str[1], str [2], str[3], str[4], str[5], str[6], Convert.ToInt32(str[7]), str[8], str[9], str[10], str[11]);
The entire code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace Unit4IP
{
//used to sort in asceding and descending order
public struct Candidate:IComparable
{
public char[] _FirstName;
public char[] _LastName;
public char[] _Company;
public char[] _Address;
public char[] _City;
public char[] _Country;
public char[] _State;
public char[] _Phone;
public char[] _Fax;
public char[] _Email;
public char[] _Web;
public int _zip;
//for comparing objects
public int CompareTo(object obj)
{
Candidate Candidate2 = (Candidate)obj;
return _LastName.ToString().CompareTo(Candidate2._LastName.ToString());
}
//implements sorting based on assignments such as zip, lastname, etc.
public int CompareTo(Candidate Candidate2,
CandidateComparer.ComparisonType comptype)
{
if(comptype==CandidateComparer.ComparisonType.Lastname)
{
String _LName = new String(_LastName);
String LName = new String(Candidate2._LastName);
return _LName.CompareTo(LName);// Convert Character Array to String because CompareTo Works efficiently with Strings
}
else
{
return Candidate2._zip.CompareTo(_zip); // compareto values that are interchanged in descending order
}
}
//Constructor of Candidate Structure
public Candidate(string FirstName, string LastName, string Company, string Address, string City, string Country, string State, int zip, string Phone, string Fax, string Email, string Web)
{
_FirstName = new char[12];
_LastName = new char[16];
_Company = new char[32];
_Address = new char[32];
_City = new char[24];
_Country = new char[24];
_State = new char[2];
_Phone = new char[12];
_Fax = new char[12];
_Email = new char[32];
_Web = new char[42];
_FirstName = FirstName.ToCharArray();
_LastName = LastName.ToCharArray();
_Company = Company.ToCharArray();
_Address = Address.ToCharArray();
_City = City.ToCharArray();
_Country = Country.ToCharArray();
_State = State.ToCharArray();
_zip = zip;
_Phone = Phone.ToCharArray();
_Fax = Fax.ToCharArray();
_Email = Email.ToCharArray();
_Web = Web.ToCharArray();
}
//Implement IComparer Interface as nested structure
public struct CandidateComparer : IComparer
{
public enum ComparisonType
{ Lastname = 1, zip = 2 }
private ComparisonType _comparisonType;
public ComparisonType comptype
{
get { return _comparisonType; }
set { _comparisonType = value; }
}
public int Compare(object x, object y)
{
Candidate Candidate1 = (Candidate)x;
Candidate Candidate2 = (Candidate)y;
return Candidate1.CompareTo(Candidate2, _comparisonType);
}
}
}
class Program
{
static void Main(string[] args)
{
ArrayList ArrayTest = new ArrayList();
//Loading of File 'ITCO321_U4_sample_data.csv' into ArraList. File only holds values, no heading i.e. remove headings
StreamReader stream1 = File.OpenText("c:\\Users\\Cdhss\\Documents\\ITCO321_U4IP_sample_data-2.csv");
string recdata = null;
while ((recdata = stream1.ReadLine()) != null)
{
string[] str = recdata.Split(',');
Candidate newrec = new Candidate(str[0], str[1], str [2], str[3], str[4], str[5], str[6], Convert.ToInt32(str[7]), str[8], str[9], str[10], str[11]);
ArrayTest.Add(newrec);//add struct object into ArrayList
}
//Traversing of Records
Console.WriteLine("Traversing Records");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname=new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
string address=new String(Candidate1._Address);
string city=new String(Candidate1._City);
string country = new String(Candidate1._Country);
string phone = new String(Candidate1._Phone);
string fax = new String(Candidate1._Fax);
string email=new String(Candidate1._Email);
string web = new String(Candidate1._Web);
Console.WriteLine( fname + "," + lname + "," + company + "," + address + "," + city + "," + country + "," + Candidate1._zip + "," + phone + "," + fax + "," + email + "," + web);
}
Candidate.CandidateComparer comparer = new Candidate.CandidateComparer();
//Sort by Lastname in ascending order
comparer.comptype = Candidate.CandidateComparer.ComparisonType.Lastname;
ArrayTest.Sort(comparer);
Console.WriteLine("Sorting of Elements by LastName");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname = new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
Console.WriteLine("\t" + fname + "," + lname + "," + company);
}
// Data sorted in desending order of ZIP field
comparer.comptype = Candidate.CandidateComparer.ComparisonType.zip;
ArrayTest.Sort(comparer);
Console.WriteLine("Sorting of Elements by Zip");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname = new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
Console.WriteLine("\t" + fname + "," + lname + "," + company + "," + Candidate1._zip);
}
//Display Records of 'NY' State
Console.WriteLine("Display Records of NY State");
foreach (Candidate Candidate1 in ArrayTest)
{
string fname = new String(Candidate1._FirstName);
string lname = new String(Candidate1._LastName);
string company = new String(Candidate1._Company);
string address = new String(Candidate1._Address);
string city = new String(Candidate1._City);
string country = new String(Candidate1._Country);
string phone = new String(Candidate1._Phone);
string fax = new String(Candidate1._Fax);
string email = new String(Candidate1._Email);
string web = new String(Candidate1._Web);
if (new String(Candidate1._State).Contains("NY"))
Console.WriteLine(fname + "," + lname + "," + company + "," + address + "," + city + "," + country + "," + Candidate1._zip + "," + phone + "," + fax + "," + email + "," + web);
}
Console.Read();
}
}
}
Your problem is in your call to Convert.ToInt32. Whatever string you are passing can't be parsed as an int.
A good solution here might be to use the some structured exception handling, either with try catch blocks or Int32.TryParse(string) for example you could do this
int intValue;
if (Int32.TryParse(str[7], out intValue))
{
//Do some thing with the int value
}
else
{
throw new Exception("Some informative error message, probably using string.Format to include the string you tried to parse");
}
TryParse returns true if the parse is successfull, false if it is not, and puts the parsed integer value in the second out parameter.
A few other comments on you code to help you out.
No one uses ArrayLists in C# anymore. Generics were introduced a long time ago, and it is almost always better, from a standpoint of both type safety and speed to use a List (Look up C# generics if you don't know what they are).
You don't need to copy the candidate properties in your foreach loop into new variables.
Give more informative variable names. Readability is the single most important quality in good code. fname should be firstName, recdata should be recievedData. Key strokes are cheap in a world with tab completion.

Html.ActionLink does not display new lines

I have this problem
string text = Html.Raw(immobileTmp.Localita + "\n" + immobileTmp.PrezzoVendita).ToString();
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
but then no new line is in output just <br /> between the 2 strings.
Then I tried
string text = Html.Raw(HttpUtility.HtmlEncode(immobileTmp.Localita + "\n" + immobileTmp.PrezzoVendita).Replace("\n", "<br/>")).ToHtmlString();
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
but had no better luck.
Any ideas?
I guess you need to insert two </ br>, did you tried that ?
UPDATE
Try Environment.NewLine, like that:
string text = Html.Raw(immobileTmp.Localita + Environment.NewLine + immobileTmp.PrezzoVendita).ToString();
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
Try this:
String s1 = (immobileTmp.Localita).ToString() + " ";
String s2 = (immobileTmp.PrezzoVendita).ToString();
String s = s1 + s2
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + s1.Length)) != -1) {
sb.replace(i, i + 1, "\n");
}
string text = Html.Raw(s);
If you join the strings with Environment.NewLine wrapping the tag in a <pre> splits the lines as you want, as in this sample:
#{
string sep = Environment.NewLine;
string text = Html.Raw(immobileTmp.Localita + sep + immobileTmp.PrezzoVendita).ToString();
}
<pre>
#Html.ActionLink(text, "DettaglioImmobile", "Immobili", new { id = immobileTmp.Id }, null)
</pre>
Gotcha: the text will be formatted as monospaced (because of the <pre>) but CSS can take care of that (<pre class="blah">...).

Delimiter Replacement Approach

I’d like to create a method to replace delimiters for the intended target use (html email, log, database). The delimiters are constant so I’d like to be able to reference a object that maps recognizable names to string values (semicolon = “;”, htmlLineBreak = “<br/>”, etc.). Is there a better means to do this than this below?
public static class Utilities
{
public string ReplaceDelimiter(string content
, Delimiter currentDelimiter, Delimiter outputDelimiter)
{
return content.Replace(currentDelimiter.ToString()
, outputDelimiter.ToString());
}
}
public class Delimiter
{
public const string comma = ",";
public const string semicolon = ";";
public const string colon = ":";
public const string lineBreak = "\r\n";
public const string htmlLineBreak = "<br/>";
}
Edited following comments:
A use case would be when I want to log an error to different targets and send the same contents (formatted differently) in an email. The log may go to a database column (want key/value with semicolon delimiter) or log file (want delimiter to be line breaks). The email would be HTML so want the delimiter to be replaced with <br/>.
Below would be an excerpt from a logging method that has a few parameters including the actual Exception:
StringBuilder delimitedMessage = new StringBuilder();
delimitedMessage.Append("Date=" + DateTime.Now.ToShortDateString() + ";");
delimitedMessage.Append("Time=" + DateTime.Now.ToLongTimeString() + ";");
delimitedMessage.Append("Source=" + objException.Source.ToString().Trim() + ";");
delimitedMessage.Append("Method=" + objException.TargetSite.Name.ToString() + ";");
delimitedMessage.Append("Erring Method=" + methodName + ";");
delimitedMessage.Append("Computer=" + System.Environment.MachineName.ToString() + ";");
delimitedMessage.Append("Log Message=" + logMessage + ";");
delimitedMessage.Append("Exception Error=" + objException.Message.ToString().Trim() + ";");
delimitedMessage.Append("Severity=" + severity.ToString() + ";");
delimitedMessage.Append("Stack Trace=" + objException.StackTrace.ToString().Trim() + ";");
contentToLog = delimitedMessage.ToString();
WriteToDb(contentToLog);
WriteToLog(Utilities.ReplaceDelimiter(contentToLog, Delimiter.semicolon, Delimiter.lineBreak));
SendEmail(Utilities.ReplaceDelimiter(contentToLog, Delimiter.semicolon, Delimiter.htmlLineBreak));
Code
public class Delimiter {
public static readonly Delimiter
HtmlLineBreak=new Delimiter {
Value="<br/>"
},
LineBreak=new Delimiter {
Value="\r\n"
},
Semicolon=new Delimiter {
Value=";"
},
Colon=new Delimiter {
Value=":"
},
Comma=new Delimiter {
Value=","
};
public override String ToString() {
return Value;
}
public String Value {
get;
set;
}
}
Test
var t=Utilities.ReplaceDelimiter("123\r\n", Delimiter.LineBreak, Delimiter.HtmlLineBreak);
Debug.Print("{0}", t);
Output
123<br/>

Categories

Resources