C# Write Data to a text File - c#

I got a homework assignment here. I've created a form with 4 text boxes for data entry, Account #, First Name, Last Name, Balance. I have four buttons, Create File, Save data to file, clear, and exit. Basically all the program does is create a text file, then I input my data into the text boxes, then I hit save data file which will write the data to the text file I have created. Clear and Exit are already done, and I have the program working as far as creating the text file, now I just need someone to point me in the right direction on how to actually write the data I entered into the text file. Here is my code, Thanks in advance
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Chapter_17_Ex.Sample_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCreate_Click(object sender, EventArgs e)
{
SaveFileDialog file = new SaveFileDialog();
file.FileName = "client.txt";
file.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
file.ShowDialog();
StreamWriter filewrite = new StreamWriter(file.FileName);
}
private void btnSave_Click(object sender, EventArgs e)
{
TextWriter file = new TextWriter
}
private void btnClear_Click(object sender, EventArgs e)
{
txtAccount.Clear();
txtBalance.Clear();
txtFirstName.Clear();
txtLastName.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

You're on the right track with creating that StreamWriter instance. What you want to do now is use the WriteLine() method of that class. It's also a good idea to wrap that StreamWriter instance in a using block:
private void btnCreate_Click(object sender, EventArgs e)
{
SaveFileDialog file = new SaveFileDialog();
file.FileName = "client.txt";
file.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
file.ShowDialog();
using(StreamWriter filewrite = new StreamWriter(file.FileName))
{
filewrite.WriteLine( String.Format("First Name is {0}", txtFirstName.Text) );
//use Write() or WriteLine() again as needed.
}
}

For the file create you can use:
File.Create(file.FileName).Close(); // replace the StreamWriter code with this
For the simplest way to write into that file:
string line = string.Join(",", txtAccount.Text, txtBalance.Text, txtFirstName.Text, txtLastName.Text) + System.Environment.NewLine;
File.AppendAllText(file.FileName, line);
You also need to move the 'SaveFileDialog file' to be a class field, not a method local variable.
You didn't specify the output format. What I chose is CSV... but there's no "escaping" of the input, which needs to be done to prevent inputting commas from messing up the output. That part is up to you.
Note the use of File.Create and File.AppendAllText - these save you from having to put using around the actual I/O.

Related

Return an updated list by clicking a button in C#

I have a a simple Form, with a panel that holds a question with four CheckButtons as answers.
The users will go through the form and select the answer for each Question.
Once they click the button to accept the answer ("buttonNewAnswer_Click" below in the code)
the answer gets consolidated in a List named "answers" and then I write that into "results" and format it so I can write one line to a .csv file.
Once all the Questions are covered, the users will click "buttonExit_Click" button
and that will write the "results" to the .csv and also exit the Application.
Unfortunatelly I cannot get the "results" list from the "buttonNewAnswer_Click" to "buttonExit_Click".
Thank you for your help/suggestions.
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SIMPLE_FORM
{
public partial class Form1 : Form
{
//public List<String> results = new List<String>();
string myCsvFileTest = #"myFile.csv"
// Button to update the answers list
private void buttonNewAnswer_Click(object sender, EventArgs e)
{
// Algorithm to update the "answers" list
var results = new StringBuilder();
foreach (var i in answers)
{
results.AppendFormat("{0},", i.ToString());
}
}
// Button to write the results to a .csv and then close the application
private void buttonExit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Press \"Yes\" to confirm closing the Application", " ", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
using (StreamWriter writer = new StreamWriter(myCsvFileTest, true, Encoding.UTF8))
{
writer.WriteLine(results);
}
System.Windows.Forms.Application.Exit();
}
else
{
this.Activate();
}
}
I'm trying to get the "results" list from the "buttonNewAnswer_Click" and use it somewhere else in the code such as "buttonExit_Click" to write to a .csv
You need to declare the results object as a Form1 class member.
Right now, you are defining it as a local variable in buttonNewAnswer_Click function - so it's destroyed once the function ends.
Simplified code based on the code in the question:
public partial class Form1 : Form
{
// declare and allocate
StringBuilder results = new StringBuilder();
private void buttonNewAnswer_Click(object sender, EventArgs e)
{
// fill the results object
foreach (var i in answers)
{
results.AppendFormat("{0},", i.ToString());
}
}
private void buttonExit_Click(object sender, EventArgs e)
{
// you can use the result here.
// results
}
}

checkedlistbox in C#, display only file name, not full path

I am trying to select a bunch of files and put the names into a checkedlistbox but it always displays the full directory path with the filename. I only want the user to see the file name but I want to preserve the path inside the code so when the user clicks a button the program can still find the files and operate on them.
My question has already been asked on another forum but I can't seem to get the expected results, currently, my code does as follows:
user clicks button_1: User selects folder containing files
all CSV files with only their file name in the checkedlistbox are displayed, with a message box appearing displaying their full paths. The user proceeds to check necessary files.
User clicks button_2: Displays a message box with the checked filenames, but not the full file paths, of which I am trying to retrieve.
Any help in this would be most appreciated thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace SelectFiles
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
checkedListBox1.CheckOnClick = true;
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
checkedListBox1.Items.Clear();
string[] files = Directory.GetFiles(fbd.SelectedPath);
List<FileInfo> excel_files = new List<FileInfo>();
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
MessageBox.Show((f.FullName));
excel_files.Add(f);
}
BindingSource bs = new BindingSource();
bs.DataSource = excel_files;
checkedListBox1.DataSource = bs;
checkedListBox1.DisplayMember = "Name";//Path.GetFileName(file);
}
}
private void button2_Click_1(object sender, EventArgs e)
{
List<FileInfo> list_all_excelfiles = new List<FileInfo>();
foreach (FileInfo item in checkedListBox1.CheckedItems)
{
list_all_excelfiles.Add(item);
MessageBox.Show(Path.GetFileName(item.FullName));
}
}
}
}
If I understood correctly, you want to get the file full path when user click on button2.
This can be achieved by modifying your code.
In the button2 event, are asking for Path.GetFileName
Change it to
Path.GetFullPath
which will return the full path of the file.
Your code should be looks like :
private void button2_Click_1(object sender, EventArgs e)
{
List<FileInfo> list_all_excelfiles = new List<FileInfo>();
foreach (FileInfo item in checkedListBox1.CheckedItems)
{
list_all_excelfiles.Add(item);
MessageBox.Show(Path.GetFullPath(item.Name));
}
}
Note : in your code, you are trying to clear the items from checkedListBox1 by Clear() method but you'll face an exception.
System.ArgumentException: 'Items collection cannot be modified when
the DataSource property is set.'
and that's because you added a data source already !
instead use :
checkedListBox1.DataSource = null;

System.Io is not working properly

I want to copy some text on textbox2 to a txt file.I want to create a kk.txt file after clicking the button and need to store textbox2 text to that kk file.
Here is the code i tried but it only create kk.txt file and not storing textbox2 data.
private void button6_Click(object sender, EventArgs e)
{
//textBox4.Text +=Clipboard.GetText()+Environment.NewLine;
Clipboard.SetText(textBox2.Text);
System.IO.File.Create(#"C:/Ebaycodes/kk.txt");
string path = #"C:/Ebaycodes/kk.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(textBox2.Text);
sw.Dispose();
}
}
}
could somebody help me to fix this error.
The problem is your if statement, it only runs if the file doesn't exist. You created it, so it does exist, and the if doesn't run. You can change your entire routine to this:
private void button6_Click(object sender, EventArgs e)
{
Clipboard.SetText(textBox2.Text);
File.WriteAllText(#"c:\Ebaycodes\kk.txt", textbox2.Text);
}

Log deleted files when button is clicked? Log all files (deleted and undeleted)

I am writing an application to delete file on a test folder that are over 6 months, the application works fine as I have tested it, I wanted to create a log file to keep track of the name of the deleted files for audit purpose.
but with the scirpt below it does record all the files (deleted and undeleted), all I need is just record the date and time and the name of the deleted files.
Thank you
Script Below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Delete_PDF_Files
{
public partial class Form1 : Form
{
private string strLogText;
public Form1()
{
InitializeComponent();
}
private void btnCheck_Click(object sender, EventArgs e)
{
// check the number of file in the CPS directory on S drive
listBox1.Items.Clear();
string[] files = System.IO.Directory.GetFiles(#"C:\test\"); // #"S:\CPS Papers\"
this.listBox1.Items.AddRange(files);
textBox1.Text = listBox1.Items.Count.ToString();
}
// delete button to delete files over 6 months from CPS folder
private void btnDelete_Click(object sender, EventArgs e)
{
string[] files = System.IO.Directory.GetFiles(#"C:\test\"); //S:\CPS Papers test C:\test\
foreach (string file in files)
{
System.IO.FileInfo fi = new System.IO.FileInfo(file);
if (fi.LastWriteTime < DateTime.Now.AddMonths(-6))
fi.Delete();
// Create a writer and open the file: //C:\test\log
System.IO.StreamWriter log;
if (!System.IO.File.Exists("C:\\test\\log\\logfile.txt"))
{
log = new System.IO.StreamWriter("C:\\test\\log\\logfile.txt");
}
else
{
log = File.AppendText("C:\\test\\log\\logfile.txt");
}
// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();
log.WriteLine();
// Close the stream:
log.Close();
}
}
// Exit button
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Replace you delete code with this one:
private void btnDelete_Click(object sender, EventArgs e)
{
string[] files = System.IO.Directory.GetFiles(#"C:\test\"); //S:\CPS Papers test C:\test\
foreach (string file in files)
{
System.IO.FileInfo fi = new System.IO.FileInfo(file);
//if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))
if (fi.LastWriteTime < DateTime.Now.AddMonths(-6))
{
fi.Delete();
using (StreamWriter writer = File.AppendText("C:\\test\\log\\logfile.txt"))
{
writer.Write("File: " + file + " deleted at : "+DateTime.Now);
writer.WriteLine("----------------------------------------------------");
writer.Flush();
writer.Close();
}
}
}
}
Instead of using custom logging as you are doing I would recommend that you use a good library like Log4Net. Why reinvent the wheel? I know that it has a small learning curve time but once you get to know you you can easily integrate it in any new projects.
By just adding a config section to your app.config as given here and a few lines of code you should be ready to go.
A good tutorial on Log4Net can be found here

How to switch directories using C#?

(This is a continuation of the discussion on this question)
I have code that looks in a specific folder in the C: drive. It can tell what is in that folder, and gets what the user selects. But the problem is switching to a new Data folder to get the code from.
All the code necessary to run the program is kept in the Data folder, the company I am interning with wants to be able to switch Data folders so they can show their software off better, and have it geared towards whoever they are showing it to.
So basically my program needs to switch data folders so the company can show their software better.
Ill post all my code, its not much, so you guys can look at all of it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string defaultPath = #"C:\Mavro\MavBridge\";
public Form1()
{
InitializeComponent();
dropdown();
}
private void button1_Click(object sender, EventArgs e)
{
//some sort of code to switch directory before close goes here
MessageBox.Show("Data folder has been changed.", "Done");
Application.Exit();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string path = comboBox1.SelectedItem.ToString();
defaultPath = path;
}
private void buttonTest_Click_1(object sender, EventArgs e)
{
}
public void dropdown()
{
string[] dispDirectories = Directory.GetDirectories(defaultPath, "Data*");
comboBox1.Items.Clear();
comboBox1.Items.AddRange(dispDirectories);
}
}
}
To answer your second question, about stripping the Default Path from the combobox display
//Where you load your directories
string[] dispDirectories = Directory.GetDirectories(#"c:\", "*.*");
// so here we will iterate through all the directories found and remove the default path from it.
for (int i=0;i<dispDirectories.Count();i++)
dispDirectories[i]=dispDirectories[i].Remove(0, defaultPath.Length);
Then where you set your path change to this. Because we removed the default Path we now have to add it again.
string path = defaultPath+comboBox1.SelectedItem.ToString();
defaultPath = path;
Look at your button1_Click method. Change your message Box to
MessageBox.Show("Data folder has been changed to "+defaultPath,"Done");
private void button1_Click(object sender, EventArgs e)
{
//some sort of code to switch directory before close goes here
MessageBox.Show("Data folder has been changed to "+defaultPath,"Done");
Application.Exit();
}
you will see that you have already changed the default Path
EDIT(#K'Leg Suggestion to make answer more clear): If you want to get the subdirectories, after you make your first selection you should call method dropdown() in comboBox1_SelectedIndexChanged
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string path = comboBox1.SelectedItem.ToString();
defaultPath = path;
dropdown();
}
A better would be receive default path as parameter in dropdown(), something on the following line
public void dropdown(string defaultPath)
{
string[] dispDirectories = Directory.GetDirectories(defaultPath, "Data*");
comboBox1.Items.Clear();
comboBox1.Items.AddRange(dispDirectories);
}
and then call dropdown method in comboBox1_SelectedIndexChanged as:
dropdown(comboBox1.SelectedItem.ToString());
EDIT: (based on the comments on OP) the problem is the filter you are specifying for the GetDirecotries, for every path you pass to it, it looks for folder starting with Data and then any characters, for example Data.Apple, now when you set your path to Data.Apple, there it again looks for folder which should start with Data, you may pass the filter in the dropdown method on some condition
you may define the method dropdown as:
public void dropdown(string defaultPath, string filter)
{
string[] dispDirectories = Directory.GetDirectories(defaultPath, filter);
comboBox1.Items.Clear();
comboBox1.Items.AddRange(dispDirectories);
}
Then you can call the dropdown for the first time as :
public Form1()
{
InitializeComponent();
dropdown(#"C:\Mavro\MavBridge\","Data*");
}
and then in the SelectedIndexChanged as:
dropdown(comboBox1.SelectedItem.ToString(),"*"); // * means select all

Categories

Resources