CsvHelper not adding line breaks [duplicate] - c#

I would like to export my class in .csv file, i follow this comment : https://stackoverflow.com/a/38088636/10152334
but when i export (in Buses_Data.Buses_List), i have wrong data output, all data are on same line :
public void ExportToCSV(Buses_Data classToExport, string filepath)
{
try
{
if (File.Exists(filepath))
{
Console.WriteLine("Le fichier existe");
System.IO.File.Delete(filepath);
Console.WriteLine("l'ancien fichier à été supprimé");
}
Console.WriteLine("Export :...");
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
}
}
Console.WriteLine("Export CSV: OK");
}
catch (Exception i)
{
Console.WriteLine("Error ! " + i);
}
}
I don't know why the code doesn't work
Edit :
Wrong output:
Right output (Data not corresponding)
Edit 2 :
I tried this comment : Enforce LF line endings with CsvHelper
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
sw.NewLine = "\n";
cw.NextRecord();
}
}
I have better result but i Bus N°1 is on first line, not in second line
Solution :
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
cw.NextRecord();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
//sw.NewLine = "\n";
cw.NextRecord();
}
}

Based on answer of GitHub issue, written by Josh Close:
You need to call NextRecord() when you're done writing the header.
This is so you can write more fields manually before or after.
I tried it, it works well.

Have you tried CsvWriter.NextRecord?
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
cw.NextRecord();
}

Related

Convert CSV in XML file with C#

I wrote this piece of code that allows me to read a CSV file and convert it to an XML file.
I have a problem, if inside the CSV file there are semicolons (;) the program cannot read the data instead, if there are commas (,) that delimit the words the program can read the data and to insert them correctly in the XML file.
could you find a way to replace the semicolon (;) with the comma (,)?
Thank you very much!! :)
This is the code:
writer.WriteStartDocument();
writer.WriteStartElement("DC8_Recipes");
using (CsvReader reader = new CsvReader(path))
{
reader.ReadHeaders();
while (reader.ReadRecord())
{
writer.WriteStartElement("DC8_Recipes");
writer.WriteAttributeString("PlantNo", reader["id_imp"]);
writer.WriteAttributeString("No", reader["nome_frm"]);
writer.WriteAttributeString("Name", reader["desc_frm"]);
writer.WriteEndElement();
}
reader.Close();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
logText.Text += DateTime.Now + " Convertion Completed\n";
logText.Text += DateTime.Now + " Saving file to: " + savepath + "\n";
try
{
logText.Text += DateTime.Now + " File save completed!\n";
logText.Text += DateTime.Now + " process END\n";
}
catch
{
}
}
You can pass into CsvReader constructor a CsvConfiguration to change the default delimiter (which is based on the current CultureInfo):
The culture is used to determine the default delimiter, default line ending, and formatting when type converting.
using (var csv = new CsvReader(writer, new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = ","
}))
{
csv.Read();
}
You could write your own CsvReader:
public static List<Model> ReadCsv(string path)
{
var modelList = new List<Model>();
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var streamReader = new StreamReader(fileStream, Encoding.Default))
{
while (!streamReader.EndOfStream)
{
var line = streamReader.ReadLine();
if (string.IsNullOrEmpty(line))
{
continue;
}
var splittedLine = line.Split(';');
var model = new Model();
for (var i = 0; i < splittedLine.Length; i++)
{
switch (i)
{
case 0:
model.FirstColumn = splittedLine[i];
break;
case 1:
model.SecondColumn = splittedLine[i];
break;
case 2:
model.ThirdColumn = Convert.ToInt32(splittedLine[i]);
break;
}
}
modelList.Add(model);
}
}
}
return modelList;
}

Streamwriter file is not being created

I'm using the code below to break apart a large text file into smaller files based on the logic you can see here. I'm getting an error on the File.WriteAllText line saying that tempfile doesn't exist. The flow is one header record, followed by multiple report data rows, followed by one end of report line, then it starts over again. Does anyone know why my temp file wouldn't be created here, what am I missing? Thanks.
private static void SplitFile()
{
StreamReader sr = new StreamReader($"{_processDir}{_processFile}");
StreamWriter sw = null;
string fileName = string.Empty;
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (line.Split('\t')[0] == "FILEIDENTIFIER")
{
//line is a header record
sw = new StreamWriter("{_processDir}tempfile.txt", false);
sw.WriteLine(line);
}
else if (line.Contains("END OF\tREPORT"))
{
//line is end of report
sw.Close();
File.WriteAllText($"{_processDir}{fileName}.txt", File.ReadAllText($"{_processDir}tempfile.txt"));
}
else
{
//line is a report datarow
fileName = line.Split('\t')[0];
sw.WriteLine(line);
}
}
}
This code is getting you problem :
sw = new StreamWriter("{_processDir}tempfile.txt", false);
Use string interpolation with above code :
sw = new StreamWriter($"{_processDir}tempfile.txt", false);
You can check that where the streamwriter has written the data.

Streamwriter, remove whole line where a specific character is found

Maybe I'm overthinking this. I've got a working method for writing to a text file, and reading from it.
Writing:
public void SaveNotes()
{
using (StreamWriter save= new StreamWriter("notes.txt", true))
{
foreach (var element in collection)
{
spara.Write(element.Prio+ " " + element.Note+ "\n");
}
}
}
Now I'm trying to design a method that looks for any '0' in my list, and overwrite the entire line.
Is there any easier way to tell the program that all lines containing a '0' should be overwritten with blankspaces? Any input much appreciated.
public static void Delete(Note note)
{
using (StreamWriter remove = new StreamWriter("notes.txt"))
{
Regex rgx = new Regex("");
foreach (var element in collection)
{
while (element.Notering.Contains("0"))
{
rgx.Replace(element.Note, "");
rgx.Replace(element.Prio, "");
}
}
}
}
Why don't you combine two of them?
public void SaveNotes()
{
using (StreamWriter save= new StreamWriter("notes.txt", true))
{
foreach (var element in collection)
{
if (element.Prio.IndexOf('\0') < 0 && element.Note.IndexOf('\0') < 0)
spara.Write(element.Prio+ " " + element.Note+ "\n");
else spara.Write(" \n");
}
}
}

Saving from List<T> to txt

I want my program to read from two text files into one List<T>.
The List<T> is sorting and cleaning duplicates.
I want the List<T> to save (after sorting and cleaning) to a txt file.
But when I looked in the result txt file, I found this message:
System.Collections.Generic.List`1[System.String]
Does anyone have an idea how I could fix this error?
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Uniqpass
{
class Program
{
static void Main(string[] args)
{
String pfad = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\";
String pfad2 = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\";
String speichern = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\ausgabe.txt";
String datei = "text1.txt";
String datei2 = "text2.txt";
try
{
//Einlesen TxT 1
List<String> pass1 = new List<String>();
StreamReader sr1 = new StreamReader(pfad + datei);
while (sr1.Peek() > -1)
{
pass1.Add(sr1.ReadLine());
}
sr1.Close();
//Einlesen TxT 2
StreamReader sr2 = new StreamReader(pfad2 + datei2);
while (sr2.Peek() > -1)
{
pass1.Add(sr2.ReadLine());
}
sr2.Close();
List<String> ausgabeListe = pass1.Distinct().ToList();
ausgabeListe.Sort();
ausgabeListe.ForEach(Console.WriteLine);
StreamWriter file = new System.IO.StreamWriter(speichern);
file.WriteLine(ausgabeListe);
file.Close();
}
catch (Exception)
{
Console.WriteLine("Error");
}
Console.ReadKey();
}
}
}
There's a handy little method File.WriteAllLines -- no need to open a StreamWriter yourself:
In .net 4:
File.WriteAllLines(speichern, ausgabeListe);
In .net 3.5:
File.WriteAllLines(speichern, ausgabeListe.ToArray());
Likewise, you could replace your reading logic with File.ReadAllLines, which returns an array of strings (use ToList() on that if you want a List<string>).
So, in fact, your complete code could be reduced to:
// Input
List<String> data = File.ReadAllLines(pfad + datei)
.Concat(File.ReadAllLines(pfad2 + datei2))
.Distinct().ToList();
// Processing
data.Sort();
// Output
data.ForEach(Console.WriteLine);
File.WriteAllLines(speichern, data);
It's this line which writes the ToString representation of the List, resulting into the text line you got:
StreamWriter file = new System.IO.StreamWriter(speichern);
file.WriteLine(ausgabeListe);
file.Close();
Instead you want to write each line.
StreamWriter file = new System.IO.StreamWriter(speichern);
ausgabeListe.ForEach(file.WriteLine);
file.Close();
Loop through the list, writing each line individually:
StreamWriter file = new System.IO.StreamWriter(speichern);
foreach(string line in ausgabeListe)
file.WriteLine(line);
file.Close();
Try the code below:
StreamWriter writer = new StreamWriter("C:\\Users\\Alchemy\\Desktop\\c#\\InputFileFrmUser.csv");
list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};
foreach (var x in list) {
string wr = x.ProductId + " " + x.Name + "" + x.Brand + " " + x.Quantity + " " + x.Price;
writer.Flush();
writer.WriteLine(wr);
}
Console.WriteLine("--------ProductList Updated SucessFully----------------");
You are writing the list object into the file, so you see the type name.
Just as you are using ForEach to write the contents to the Console, you need to iterate over ausgabeListe, calling WriteLine() for each item in the list.
StreamWriter file = new System.IO.StreamWriter(speichern);
foreach(string x in ausgabeListe)
file.WriteLine(x);
file.Close();
I am using the LINQ like below to write each line to text file.
var myList=new List<string>
{
"Hello",
"World"
};
using (var file = new StreamWriter("myfile.txt"))
{
myList.ForEach(v=>file.WriteLine(v));
}

Open existing file, append a single line

I want to open a text file, append a single line to it, then close it.
You can use File.AppendAllText for that:
File.AppendAllText(#"c:\path\file.txt", "text content" + Environment.NewLine);
using (StreamWriter w = File.AppendText("myFile.txt"))
{
w.WriteLine("hello");
}
Choice one! But the first is very simple. The last maybe util for file manipulation:
//Method 1 (I like this)
File.AppendAllLines(
"FileAppendAllLines.txt",
new string[] { "line1", "line2", "line3" });
//Method 2
File.AppendAllText(
"FileAppendAllText.txt",
"line1" + Environment.NewLine +
"line2" + Environment.NewLine +
"line3" + Environment.NewLine);
//Method 3
using (StreamWriter stream = File.AppendText("FileAppendText.txt"))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 4
using (StreamWriter stream = new StreamWriter("StreamWriter.txt", true))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 5
using (StreamWriter stream = new FileInfo("FileInfo.txt").AppendText())
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
Or you could use File.AppendAllLines(string, IEnumerable<string>)
File.AppendAllLines(#"C:\Path\file.txt", new[] { "my text content" });
Might want to check out the TextWriter class.
//Open File
TextWriter tw = new StreamWriter("file.txt");
//Write to file
tw.WriteLine("test info");
//Close File
tw.Close();
The technically best way is probably this here:
private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");
if (!File.Exists(path))
throw new FileNotFoundException("File not found.", nameof(path));
using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
using (var writer = new StreamWriter(file))
{
await writer.WriteLineAsync(line);
await writer.FlushAsync();
}
}
File.AppendText will do it:
using (StreamWriter w = File.AppendText("textFile.txt"))
{
w.WriteLine ("-------HURRAY----------");
w.Flush();
}
//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}
We can use
public StreamWriter(string path, bool append);
while opening the file
string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);
First parameter is a string to hold a full file path
Second parameter is Append Mode, that in this case is made true
Writing to the file can be done with:
writer.Write(string)
or
writer.WriteLine(string)
Sample Code
private void WriteAndAppend()
{
string Path = Application.StartupPath + "\\notes.txt";
FileInfo fi = new FileInfo(Path);
StreamWriter SW;
StreamReader SR;
if (fi.Exists)
{
SR = new StreamReader(Path);
string Line = "";
while (!SR.EndOfStream) // Till the last line
{
Line = SR.ReadLine();
}
SR.Close();
int x = 0;
if (Line.Trim().Length <= 0)
{
x = 0;
}
else
{
x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
}
x++;
SW = new StreamWriter(Path, true);
SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine(x.ToString() + "." + textBox1.Text);
}
else
{
SW = new StreamWriter(Path);
SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine("1." + textBox1.Text);
}
SW.Flush();
SW.Close();
}

Categories

Resources