How to append text to an existing text file? - c#

I wrote an application that would ask the user for some details of the hotel that they are staying at, and the text does luckily get added, but if I add another person it will override the previous data that was in the file already. However, I want it to keep all of the data inputs.
Here is my code:
hotelName = txt_HotelName.Text;
ratings = txt_HotelRating.Text;
roomsNeeded = txt_RoomsNeeded.Text;
name = txt_UserName.Text;
surname = txt_UserLastname.Text;
contactDetails = txt_ContactDetail.Text;
paymentDetails = txt_PaymentMehthod.Text;
paymentDate = txt_PaymentDate.Text;
using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))
{
sw.WriteLine(txt_HotelName + Environment.NewLine + txt_HotelRating + Environment.NewLine + txt_RoomsNeeded +
Environment.NewLine + txt_UserName + Environment.NewLine + txt_UserLastname + Environment.NewLine + txt_ContactDetail +
Environment.NewLine + txt_PaymentMehthod + Environment.NewLine + txt_PaymentDate);
}
MessageBox.Show($"Thank you for using our system {txt_UserName.Text}.", "Thank you", MessageBoxButtons.OK);
So what I want is to collect all of the data, rather than having them over-write each time.

Try appending the file:
string line = string.Join(Environment.NewLine, new string[] {
ratings,
roomsNeeded,
name,
surname,
contactDetails,
paymentDetails,
paymentDate});
File.AppendAllLines("HotelDocument.txt", new string[] {line});
Edit: if you want to organize the input data, I suggest using string interpolation (C# 6.0) or formatting:
string line = string.Join(Environment.NewLine, new string[] {
$"Ratings: {ratings}",
$"Rooms need: {roomsNeeded}",
$"Name: {name}",
$"Surname: {surname}",
$"Details: {contactDetails}",
$"Payment: {paymentDetails}",
$"Payment Date: {paymentDate}");

You need to specify a unique name:
using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))
So instead of "HotelDocument.txt" maybe use the current DateTime, or even a new Guid() to be 100% unique. So something like:
var uniqueFileName = new Guid().ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(uniqueFileName))
Or are you looking to append new data within the existing HotelDocument.txt?

Related

C# Deserialize lists within a .dat file to a text box

I have created an application that will save lists to a .dat file using a binary formatter and serializing the list.
I wish to then de serialize this list and display this within a text box.
Furthermore, I have tried using a for each loop to get every object from the list, but it won't continue through the rest of the lists and stops at the first list stored within the file.
I have been tasked with binary formatter even though Ive been informed its obsolete.
`public InPerson(int iId, string sDate, string sTime, string sDuration, string sPatientname, string
sPhonenumber, string sDoctorid, string sRoomnumber, string sNurseid)
{
this.iId = iId;
this.sDate = sDate;
this.sTime = sTime;
this.sDuration = sDuration;
this.sPatientname = sPatientname;
this.sPhonenumber = sPhonenumber;
this.sDoctorid = sDoctorid;
this.sRoomnumber = sRoomnumber;
this.sNurseid = sNurseid;
}
//To String method for saving
public override string ToString()
{
return "In Person Apppointment: " + iId + System.Environment.NewLine +
"Date: " + sDate + System.Environment.NewLine +
"Time: " + sTime + System.Environment.NewLine +
"Duration: " + sDuration + System.Environment.NewLine +
"Patients Name: " + sPatientname + System.Environment.NewLine + "Patients Number: " + sPhonenumber + System.Environment.NewLine +
"Doctors ID: " + sDoctorid + System.Environment.NewLine +
"Room Number: " + sRoomnumber + System.Environment.NewLine +
"Nurse id: " + sNurseid + System.Environment.NewLine + "";
}
InPerson NewInPersonApp = new InPerson(Convert.ToInt32(txtID.Text), dateTimePickerBooking.Text, txtTime.Text, txtDuration.Text, txtPatientName.Text, txtPhoneNumber.Text, txtDoctorID.Text, txtRoomAllocated.Text, txtNurseID.Text);
List<InPerson> InPersonList = new List<InPerson>();
InPersonList.Add(NewInPersonApp);
const String filename = "appointments.dat";
FileStream outFile;
BinaryFormatter bFormatter = new BinaryFormatter();
outFile = new FileStream(filename, FileMode.Append, FileAccess.Write);
bFormatter.Serialize(outFile, InPersonList);
outFile.Close();`
`
I wish to use this code to loop every list out from the file.
`InPersonList = (List<InPerson>)bFormatter.Deserialize(inFile);
foreach (InPerson a in InPersonList)
{
txtBookings.Text += a.ToString();
}`

Increment file name by 1 if the file exists in c#

I am trying to increment the filename (e.g., "file1.csv", "file2.csv", etc.), each time a new file is generated. I followed this thread Increment the file name if the file already exists in c# but the solution is not useful for my case. What I want to do is check if the file exists in the first place and if it does write in it. If it doesn't create one and write. The problem is that if the file exists but it's from another user, I want the system to increment the file number and not write to the same file just because it exists. What I have so far:
public void saveFile()
{
int count = 0;
string title = "TimeStamp,Name,Trial,Time_spent-dist,Time_spent_tar\n";
string output = System.DateTime.Now.ToString("mm_ss_ffff") + "," +
currentScene.name.ToString() + "," +
trialNum.ToString() + "," +
timerDistractor.ToString() + "," +
timerTarget.ToString();
string fname = "User_" + count + ".csv";
string path = Path.Combine(Application.persistentDataPath, fname);
if (File.Exists(path))
{
File.AppendAllText(path, "\n" + output);
}
else
{
StreamWriter writer = new StreamWriter(path);
writer.WriteLine(title + "\n" + output);
writer.Close();
}
}
Any pointers?

How to add Column and Row header while appending data into CSV file using C#

I'm trying to insert data into CSV file using C# code. With the code I pasted below, I am able to add column header to the CSV file. But I need to add both column and row header in the CSV file for better readability. Please help me on this.
C# Code
string newFileName = "C:\\AlertReportTill_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".csv";
string AlertDetails = fromDate + "," + toDate + "," + Column1's Value + "," + Column2's Value + ","
+ Column3's Value + "," + Environment.NewLine;
if (!System.IO.File.Exists(newFileName))
{
string AlertHeader = "Weekly Report" + Environment.NewLine + "From Date" + "," + "To Date" + "," +
"ColumnHeader1" + "," + "ColumnHeader2" + "," +
"ColumnHeader3" + "," + Environment.NewLine;
System.IO.File.WriteAllText(newFileName, AlertHeader);
} //End of If Statement
System.IO.File.AppendAllText(newFileName, AlertDetails);
For better clarity, I have added an image below to help you understand my question. It would be very helpful if someone can sort this out for me. Thanks in advance.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication104
{
class Program
{
static void Main(string[] args)
{
string oldFileName = "C:\\AlertReportTill.csv";
string newFileName = string.Format("C:\\AlertReportTill_{0}.csv", DateTime.Now.ToString("yyyyMMdd_hhmmss"));
StreamReader reader = new StreamReader(oldFileName);
if (!System.IO.File.Exists(newFileName))
{
StreamWriter writer = new StreamWriter(newFileName);
writer.WriteLine("Weekly Report");
string AlertHeader = string.Join(",", new string[]
{"",
"ColumnHeader1", "ColumnHeader2", "ColumnHeader3"
});
writer.WriteLine(AlertHeader);
string line = "";
int RowCount = 0;
while ((line = reader.ReadLine()) != null)
{
List<string> AlertDetails = line.Split(new char[] { ',' }).ToList();
AlertDetails.Insert(0, "RowHeader" + ++RowCount);
writer.WriteLine(string.Join(",", AlertDetails));
}
reader.Close();
writer.Flush();
writer.Close();
} //End of If Statement
}
}
}

Add column to Excel

using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
{
if (!exists)
{
writer.WriteLine(DateTime.Now.ToLongDateString());
writer.WriteLine("REG.,BR.,BR.NAME,AC TYPE,PRODUCT,NO.OF ACS,ORG.CURRENCY BALANCE,ORG CURRENCY,BALANCE LKR");
writer.WriteLine(text.Replace("|", ","));
}
writer.WriteLine(text.Replace("|", ","));
////true is append parameter. I use this code to create Excel files. I want add new column and fill each cell with auto increment numbers.
As you didn't include the appropriate infos I take it that text includes all lines that you want to use and , is being used as the separator instead of the more commonly used ; .
The following splits this complete text into multiple lines and creates an "autoincrement" number that is appended as the last column.
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
{
if (!exists)
{
writer.WriteLine(DateTime.Now.ToLongDateString());
writer.WriteLine("REG.,BR.,BR.NAME,AC TYPE,PRODUCT,NO.OF ACS,ORG.CURRENCY BALANCE,ORG CURRENCY,BALANCE LKR");
}
var textArray = text.Replace("|", ",").split(Environment.NewLine);
int number = 0;
foreach (string text in textArray)
{
number ++;
write.WriteLine(text + "," + number.ToString());
}

Catch XML with custom Classes

I have so many clases, but I want to catch the sent and the recived information via XML ... The thing is that I don't want to create a Serializer every time i catch an XML doc, so I want to ask you if anyone know how to pack a class type into a TypeOf()
Im trying to create a function that Works something like this:
public void createXML(string fileName, string route)
{
System.Xml.Serialization.XmlSerializer serializador = new System.Xml.Serialization.XmlSerializer(typeof(THIS IS WHAT I WANNA CHANGE TO A VARIABLE PARAMETER));
System.IO.FileStream stream = new System.IO.FileStream(#""+ route + fileName + ".xml", System.IO.FileMode.Create);
}
So what I want to do is to call this function and créate an XML whenever I want, but the thing is that inside the TypeOf() command, I can't figure out a way to put different classes there.
Use generics for this task.
public void createXML<T>(string fileName, string route)
{
System.Xml.Serialization.XmlSerializer serializador = new System.Xml.Serialization.XmlSerializer(typeof(T));
System.IO.FileStream stream = new System.IO.FileStream(#""+ route + fileName + ".xml", System.IO.FileMode.Create);
}
Ok, so i got this so far and if i put the route manually it Works, if i put a custom route is brings an error message saying something about the provided route formant isnt admited, this is my code ... I get the directory, créate it if its not there, then i créate the name of the file, but when i try to créate the XML it just pops the error:
public string[] createDir(string flow, int enclosure, string transaction, string method)
{
DateTime Hoy = DateTime.Now;
libs.Catalogos objCatalogos = new libs.Catalogos();
string day, month, year, hora, min, seg, time, ruta, fileName, name;
string[] datos = new string[2];
int existe;
name = objCatalogos.convertRecinto(enclosure);
day = System.DateTime.Now.ToString("dd");
//day = "13";
month = System.DateTime.Now.ToString("MM");
year = System.DateTime.Now.ToString("yyyy");
hora = System.DateTime.Now.ToString("HH");
min = System.DateTime.Now.ToString("mm");
seg = System.DateTime.Now.ToString("ss");
time = hora + "_" + min + "_" + seg;
ruta = #"C:\inetpub\wwwroot\WsDesarrollo2\" + #"XML" + #"\Empresa_" + name + #"\Flujo_" + flow + #"\Año_" + year + #"\Mes_" + month + #"\Dia_" + day + #"\";
existe = verifyDir(ruta);
if (existe == 0)
{
Directory.CreateDirectory(ruta);
}
fileName = "" + ruta + transaction + "_" + method + "_" + time;
datos[0] = ruta;
datos[1] = fileName;
return datos;
}
public void createXML<T>(string fileName, string route, T objeto)
{
System.Xml.Serialization.XmlSerializer serializador = new System.Xml.Serialization.XmlSerializer(typeof(T));
TextWriter tw = new StreamWriter(#"" + route + #"\" + fileName + ".xml");
serializador.Serialize(tw, objeto);
}
Ok guys, i solved this issue and im just comming to post the final result, just in case anyone needs it, this is the final code where i créate a directory, or validate if it already exists and then créate an XML for any tipe of object that goes in or out of a webservice, so this is the library:
public class xmlLog
{
public int verifyDir(string dir)
{
bool tryDir;
tryDir = Directory.Exists(dir);
if (tryDir == false)
{
return 0;
}
else
{
return 1;
}
}
public string[] createDir(string flow, int enclosure, string transaction, string method)
{
DateTime Hoy = DateTime.Now;
libs.Catalogos objCatalogos = new libs.Catalogos();
string day, month, year, hora, min, seg, time, ruta, fileName, name;
string[] datos = new string[2];
int existe;
name = objCatalogos.convertRecinto(enclosure);
day = System.DateTime.Now.ToString("dd");
month = System.DateTime.Now.ToString("MM");
year = System.DateTime.Now.ToString("yyyy");
hora = System.DateTime.Now.ToString("HH");
min = System.DateTime.Now.ToString("mm");
seg = System.DateTime.Now.ToString("ss");
time = hora + "_" + min + "_" + seg;
ruta = #"C:\inetpub\wwwroot\WsDesarrollo\" + #"XML" + #"\Empresa_" + name + #"\Flujo_" + flow + #"\Año_" + year + #"\Mes_" + month + #"\Dia_" + day + #"\";
existe = verifyDir(ruta);
if (existe == 0)
{
Directory.CreateDirectory(ruta);
}
fileName = "" + ruta + transaction + "_" + method + "_" + time;
datos[0] = ruta;
datos[1] = fileName;
return datos;
}
public void createXML<T>(string route, string fileName, T objeto)
{
string file = Path.Combine(route, fileName + ".xml");
System.Xml.Serialization.XmlSerializer slzr = new System.Xml.Serialization.XmlSerializer(typeof(T));
TextWriter tw = new StreamWriter(file);
slzr.Serialize(tw, objeto);
}
}
At the end of all this mess i managed to create a new directory and create an XML with just 2 code lines every time i need them, wich are the following ones:
string[] = objXML.createDir("IN", Convert.ToInt32(recinto), M903In.transaccionAduana, "903");
objXML.createXML(paramXML[0], paramXML[1], M903In);
I know this wont work for everyone, but this is the way i managed to work with to creade dinamy routes and filenames for XML documents on a webservice.
Hopefully it helps someone :3

Categories