Save text to a text file already created - c#

So I am currently trying to do this question for tafe but am having trouble getting it to add text to the file after the first time.
"Create an application that at start up asks the user to choose an output file using a Save File Dialog Window. The application to have a “Write to File” button that when clicked will take a name and age that the user has entered into two text boxes and write them directly to the file. The user can repeat the button click action as often as they wish."
This is my current code for it:
private void Form4_Load(object sender, EventArgs e)
{
saveFileDialog1.Title = ("Choose Save Location");
saveFileDialog1.ShowDialog();
}
private void btnSendToFile_Click(object sender, EventArgs e)
{
string strName = txtName.Text;
string strAge = txtAge.Text;
string strTitles = ("Name \t\t Age");
string strCombined = strTitles + "\n" + (strName + "\t\t" + strAge);
System.IO.StreamWriter OutFile;
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
OutFile = System.IO.File.CreateText(saveFileDialog1.FileName);
OutFile.WriteLine(strCombined);
OutFile.Close();
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
StreamWriter AddFile = File.AppendText(saveFileDialog1.FileName);
AddFile.Write(strCombined);
}
I'm not sure if I should be doing a loop or not and this is the form itself, https://gyazo.com/e2c4170d46295d6f92a35026e1f2304b
Any help is appreciated, Thanks in advance

For what you're doing you absolutely don't need to work with streams or anything that low level (you don't need to call the create methods on files and use a stream returned by it). You can directly use the methods that write or append to the file and handle all of this for you.
For example using AppendAllText will do everything for you (managing the streams, flushing and closing them, appending at the end, creating the file if it doesn't exist etc etc).
so you can replace all of this code :
System.IO.StreamWriter OutFile;
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
OutFile = System.IO.File.CreateText(saveFileDialog1.FileName);
OutFile.WriteLine(strCombined);
OutFile.Close();
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
with
File.AppendAllText(saveFileDialog1.FileName, strCombined);
I have no idea what you're doing in the code that follows it (calling appendtext, i assume you're thinking you need to append after creating?) in any case you don't need it. So if you just want to append all the text of "strcombined" at the end of the file each time you click the whole function should look like :
private void btnSendToFile_Click(object sender, EventArgs e)
{
string strName = txtName.Text;
string strAge = txtAge.Text;
string strTitles = ("Name \t\t Age");
string strCombined = strTitles + "\n" + (strName + "\t\t" + strAge);
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
File.AppendAllText(saveFileDialog1.FileName, strCombined);
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
}
Also as a side comment i would rewrite all of it as such for readability, these are suggestions and not hard rules:
1) Removed hungarian notation (Don't add a prefix to your variable to indicate it's type, it's generally frowned upon)
2) Removed a lot of the temporary variables that aren't really needed (used once in the same local function)
This makes for a much smaller and very readable function:
private void btnSendToFile_Click(object sender, EventArgs e)
{
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
File.AppendAllText(saveFileDialog1.FileName,"Name \t\t Age"+ "\n" + txtName.Text + "\t\t" + txtAge.Text);
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
}

Related

Store multiple int in a .txt file, each time on a new line

Sorry for the bad title, i didn't know how to explain it better. I just started in Csharp so its probably a dumb mistake.
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = "CPU Usage" + " " + (int)cpuCounter.NextValue() + "%";
string[] usageCPUay = { label1.Text };
System.IO.File.WriteAllLines(#"C:\Users\Filip\Desktop\CPUOutput.txt", usageCPUay);
}
So this is the code I have issues with and can't understand how to fix it. I tried with streamwriter but I got the same issues. I want to make the output the cpuCounter gives to store in a txt file. But every time it just writes the latest CPU Usage and not every one. Like this wrong output. I want it to type all the cpu usages it got and store them like that but every new one in a separate line.
Let's analyze your code:
you have a method, in the body you have label1.text which is text I assume, a string.
then you have got an array of strings, but this array contains only a single element, which is label1.text, then you write in the text file the array, which contains only a single element.
3 errors I see:
1.- the array contains a single element, therefore you are only storing a single line.
2.- at the end of the string that you are meant to record in the text file you should add "\n" for a new line.
3.- I understand from https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netcore-3.1#System_IO_File_WriteAllLines_System_String_System_String___ that it creates the file as new, therefore you may be deleting what you already have.
Solution:
Like in the example that was presented to you in the link, I would do the following:
label1.Text = "CPU Usage" + " " + (int)cpuCounter.NextValue() + "%\n";
string[] usageCPUay = { label1.Text };
if (!File.Exists(path))
{
// Create a file to write to.
File.WriteAllLines(path, usageCPUay);
}
else{
File.AppendAllText(path, usageCPUay);}

Editing some text in a text file in WPF

I am new to using forms and C # and trying to do an assignment to create a phone book. I have different options in my phone book
To Add a contact
To show all contacts
and To edit a certain contact.
I am having trouble in how to do editing when text is stored in a text file. I have the following code for my add which adds name, phone number and email. How would i be able to edit one of the names from a list of contacts that is saved in the text file?
Add Code:
private void addButton_Click(object sender, RoutedEventArgs e)
{
TextWriter writer = new StreamWriter("D:\\class1.txt", append: true);
try
{
string Name01 = firstName.Text;
string Name02 = lastName.Text;
string Phone1 = mobile.Text;
string Phone2 = homePhone.Text;
string emailadd = email.Text;
string Informtion = Name01 + "\n" + Name02 + "\n" + Phone1 + "\n" + Phone2 + "\n" + emailadd;
writer.WriteLine("---------------");
writer.WriteLine(Informtion);
MessageBox.Show("Success!! Contact information added for: " +Name01 + " " +Name02);
}
catch (Exception ex)
{
throw ex;
}
finally
{
writer.Close();
writer.Dispose();
}
}
It appears your text file is not structured. Unstructured text is very difficult to search and edit programmatically.
Try using XML or JSON formatted text instead which will allow you to work with entries much easier, especially if you use one of the many open source libraries specifically developed to work with entries in these two formats...
Let's take this XML for example:
<?xml version="1.0" encoding="UTF-8"?>
<SnomIPPhoneDirectory>
<Title>PhoneList - Snom</Title>
<DirectoryEntry>
<Name>Friend, First</Name>
<Telephone>555-456-7890</Telephone>
</DirectoryEntry>
<DirectoryEntry>
<Name>Person, Second</Name>
<Telephone>555-654-0987</Telephone>
</DirectoryEntry>
<SoftKeyItem>
<Name>F1</Name>
<Label>Dial</Label>
<SoftKey>F_ENTER</SoftKey>
</SoftKeyItem>
</SnomIPPhoneDirectory>
Using a library or even XML functionality built into .NET framework it would be trivial to work with phone book entries in the object oriented way where you would not have to do any string parsing.

columns combining when c# appends to csv

We've created a desktop timer that our users are using to track their daily tasks and projects. It outputs data to a .csv file when they close the application. Occasionally they are going to need to manually update the csv file to either take time off or add time. When they have been doing this in the current state after they save all the columns are combined into column A. I am unclear on what is causing this and tried to research encoding but couldn't find anything I could relate to this scenario.
Full form1.cs: full form1.cs code
Code related to csv:
//event handler for the closing event -- the output dump is here so the timer can be used all day and captures even on an accidetnal close
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//if the file exists we don't need to write the headers so we can skip the additional line write and just append the data created
if (File.Exists(dskPath + "\\" + agentName + ".csv"))
{
using (var file = new StreamWriter(dskPath+"\\" + agentName + ".csv", true, Encoding.UTF8))
{
foreach (var data in TimerData)
{
file.WriteLine(string.Join(",", data.agentID, data.agentStatus, data.statusTime, data.startTime, data.currentDate, data.hydraTask, data.clientname, data.publishdate, data.notes));
}
file.Close();
notifyIcon1.Icon = null;
MessageBox.Show("The file for " + agentName + " has been written to G:\\Communicator Ops\\Population Health\\Pop Process\\Time Tracking\\User Data.", "Application Closed");
}
}
//if the file hasn't been created before we can drop the headers in for the columns
else
{
using (var file = new StreamWriter(dskPath +"\\"+ agentName + ".csv", true, Encoding.UTF8))
{
file.WriteLine(string.Join(",", "Agent ID", "Agent Status", "Status Time", "Start Time", "Current Date", "hydra task number", "Client Name", "Publish Date", "Notes"));
foreach (var data in TimerData)
{
file.WriteLine(string.Join(",", data.agentID, data.agentStatus, data.statusTime, data.startTime, data.currentDate, data.hydraTask, data.clientname, data.publishdate, data.notes));
}
file.Close();
notifyIcon1.Icon = null;
MessageBox.Show("The file for " + agentName + " has been written to your desktop.","Application Closed");
}
}
}
I have a theory about what might be occurring. The C# code looks OK. I think the users are opening the file in a way you were not expecting. I think they are doing the following:
1) Opening Excel and then navigating to the file location. This will cause this dialog to open:
2) They hit Next and get to step 2.
At this step they may be leaving Tab selected as the delimiter which is NOT correct. This is where they may be causing your problem.
They hit Next again
3)
Finally they hit Finish and everything ends up in column A.
If I double click on the desktop icon it seems to work OK. If I select comma as the delimiter, and uncheck Tab, that worked too.
That is my guess. Hopefully this will help you out.

Searching and Reading from file

I'm wondering if it is possible to search and read from a file and display what's in the file in a message box.
I'm wanting to search for a file by its ID, which ID is known by the user. When the user enters the ID my program opens the file which shares the same ID; eg.ID.txt in the preset folder.
when it's selected it is then read and put in a MessageBox which will then display what is in the file.
Can anyone show me how to do this?
Thanks.
//Declare variables
int TID;
private void TIDFileCreate_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");
}
private void SearchButton_Click(object sender, EventArgs e)
{
SearchID = int.Parse(searchTextBox.Text);
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\"+SearchID+".txt");
}
Can't you just use MessageBox.Show() in your SearchButton_Click method?
private void SearchButton_Click(object sender, EventArgs e)
{
SearchID = int.Parse(searchTextBox.Text);
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\"+SearchID+".txt");
System.Windows.Forms.MessageBox.Show(string.Join("\r\n", lines));
}
I think that for what you want to do you should read this:
http://msdn.microsoft.com/en-us/library/ms233843.aspx
or some similar article about serialization.
This said, if the number of IDs grow in number, you should considering the adoption of a lightweight DB, i.e. SQLite, just to name one.
Take a look at the DirectoryInfo class. Something like the following should do what you want;
DirecectoryInfo dir = new DirectoryInfo(pathToRoot);
FileInfo[] files = dir.GetFiles("Id.txt"); //if using a specific name should return 1 item
TextBox.Text = File.ReadAllText(files.FirstOrDefault().FullName);
Keep in mind I have no error handling or anything here. You'll have to add that yourself, this just shows you the key classes/methods to get the files and read their contents. There are many other options like doing GetFiles(), keeping that collection in memory and then operating on them later on.

c# change the form title by the savefile name.extension

everytime i change a file such as a .rft or .txt i want it to display the name in the title for e.g RFT Editor:docment.rft
here the code i am using atm
this.Text = "RFT Editor:" + saveFileDialog1.FileName;
hope someone can help
Your question is poorly worded. You don't describe how the result you are getting is different from what you'd like it to be.
I can only guess the problem is that "RFT Editor:" + saveFileDialog1.FileName gives you a file name with an entire path, and to get "RFT Editor:docment.rft" as in your example you'd need "RFT Editor:" + System.IO.Path.GetFileName(saveFileDialog1.FileName) instead.
Assuming you need this:
...
...
// Save clicked inside, not Cancel
if(saveFileDialog1.openDialog() == DialogResult.OK)
{
// this.Text is same as only Text - in case of current class (matter of choice)
Text = "RTF Editor: " + savefileDialog1.FileName;
...
...
}

Categories