How to prevent overwriting in a text file? - c#

I have a trouble with the following code. It should prevent overwriting records in the text file. My code is like that:
public static void WritingMethod()
{
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);
// I using the Environment.NewLine to insert new lines
Console.WriteLine(output);
Sw.WriteLine(output + Environment.NewLine);
Sw.Close();
}
It overwrites the records. I want to add records and not overwrites it.

Open your StreamWriter using File.AppendText:
using (StreamWriter Sw = File.AppendText("fileone.txt"))
{
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);
}

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();
}`

How to replace word with hyperlink?

Starting with an example, I have some keywords like
Narendra Modi, Modi, India, Speech, Parliament
And I have a story with text
Narendra Modi will give a speech in the parliament of India.
Now I want my regex to replace the keyword with the hyperlink in the story.
<a>Narendra Modi</a> will give speech in the <a>parliament</a> of <a>India.</a>
My Code for this is
var tagArray = bodykeywords.Split(',').ToList();
foreach (var tag in tagArray.OrderBy(a => a.Length))
{
var replaceTag = tag.Replace("(", "");
replaceTag = replaceTag.Replace(")", "");
DataDesc = Regex.Replace(DataDesc, "\"" + replaceTag.Trim() + "\"", " \"" + replaceTag.Trim() + "\" ");
DataDesc = Regex.Replace(DataDesc, " " + replaceTag.Trim() + ", ", " " + replaceTag.Trim() + ", ");
DataDesc = Regex.Replace(DataDesc, " " + replaceTag.Trim() + " ", " " + replaceTag.Trim() + " ");
}
Problem is I am not able to replace the word with full stop like India in the given example and Word with repetition like Narendra Modi, Modi in the keyword.

Add pause to Alexa without using SSML

Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.
Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."
I am using C# and my own https endpoint, not AWS Lambda.
Any suggestions? Otherwise I will add it as SSML. Thanks.
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("here are works of art for " + m_artist + ". ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available.";
}
else
{
m_location = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n"); // It is located on the " + dr["CurrentLocation"].ToString());
}
sql_conn_data.Close();
response.Response.OutputSpeech.Text = output.ToString();
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
UPDATE
OK. Ended up going the SSML route which looks like this:
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_location_card;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("<speak>");
output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available. <break time='1s' />";
m_location_card = "The location is not available. ";
}
else
{
m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
m_location_card = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");
}
output.Append("</speak>");
sql_conn_data.Close();
response.Response.OutputSpeech.Ssml = output.ToString();
response.Response.OutputSpeech.Type = "SSML";
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
}
There is not a way to introduce a pause in Alexa without SSML. You will need to build the ssml string and return it back to Alexa using the pause, or the cadence strings.

Writing Text File to Folder on Desktop

I'm wondering how do you write a text file to a specific location on the desktop such as C:\Users\tommy\desktop\transaction\ using StreamWriter?
private void CreateTransaction_Click(object sender, EventArgs e)
{
StreamWriter outputFile;
outputFile = File.CreateText (TID.ToString()+".txt");
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.Close();
MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + "Was Created", "Transaction File");
}
If you know the path,
FileStream fs = new FileStream(#"C:\Users\tommy\desktop\transaction\\result.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
sw.WriteLine("Initial Amount" + " " +AmountLabel.Text);
sw.WriteLine("Date Invested" +" " +DateLabel.Text);
sw.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
sw.WriteLine("Rate Chosen" + " " + RateLabel.Text);
sw.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
sw.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
sw.Flush();
sw.Close();
else create a file inside the desktop folder and do the above
Use Environment.SpecialFolder to get the path to the desktop.
string strPath = Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);

Properly formatted text output to .txt file

I'am exporting some data to a .txt file as follows:
String content;
String path=#"e:\coding\";
String name="test.txt";
path+=name;
System.IO.File.Delete(path);
for (i=0;i<row-1;i++)
{
try
{
if (r[i].points.Count() > 2)
{
content = "Route " + (i + 1).ToString() +" Truck_id:"+trk[i].truck_name.ToString()+ " Max_load="+trk[i].capacity.ToString()+ "\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine);
System.IO.File.AppendAllText(path, "Points Load Reached_AT Max_load" + Environment.NewLine);
System.IO.File.AppendAllText(path, "========================================" + Environment.NewLine);
for (int j = 0; j < (r[i].points.Count()); j++)
{
content = r[i].points[j].ToString() + " " + c[r[i].points[j]].load.ToString() +" "+ r[i].time_list[j].ToString()+" "+c[r[i].points[j]].max_load.ToString()+"\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine);
}
content = "Total " + r[i].ld.ToString() + "\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine );
content = "Route Complete: " + r[i].reach_at.ToString();
System.IO.File.AppendAllText(path, content + Environment.NewLine+Environment.NewLine);
}
}
catch (IndexOutOfRangeException e)
{
break;
}
}
As expected the output I get is not properly formatted:
The spaces are causing the text to be jumbled and not arranged. My reputation does'nt allow me to post a screenshot but I guess It can be understood what is happening.
Is there way so that the text is properly formatted neatly column wise without looking jumbled.
If you need a text, you can use tabs:
System.IO.File.AppendAllText(path, "Points\t\tLoad\t\tReached_AT\t\tMax_load" + Environment.NewLine);
// ...
content = r[i].points[j].ToString() + "\t\t " + c[r[i].points[j]].load.ToString() +"\t\t"+ r[i].time_list[j].ToString()+"\t\t"+c[r[i].points[j]].max_load.ToString()+"\n";
Just play with amount of tabs (\t for one, \t\t for two, etc...). Hope it can help.
Another solution would be to use commas:
System.IO.File.AppendAllText(path, "Points,Load,Reached_AT,Max_load" + Environment.NewLine);
and save to CSV-file (comma-separated values). Then you can import the data to Microsoft Excel or to other software.
You can find bunch full of good information on how to format the string contents in the The format item MSDN but for quick answer, an example for your string
content = "Route " + (i + 1).ToString() + " Truck_id:" + trk[i].truck_name.ToString() + " Max_load=" + trk[i].capacity.ToString() + "\n";
If we assume,
i maximum 10 digits,
Truck_name max 45 characters
capacity max 10 digits
content = String.Format("{0,-20}{1,55}{2,20} " + Environment.NewLine, "Route " + (i + 1).ToString(), " Truck_id:" + trk[i].truck_name.ToString(), " Max_load=" + trk[i].capacity.ToString());

Categories