I'm trying to create a file, add all the listbox items to the file. SO I can later on open the file and show all the listbox items again.
My current code is not working, it wont create a file or save to a existing file.
Function to get the name of thefile created / path
private void mnuFileSaveAs_Click(object sender, EventArgs e)
{
string fileName = "";
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
if(fileName == String.Empty)
{
mnuFileSaveAs_Click(sender, e);
}
else
{
fileName = sfd.FileName;
writeToFile(fileName);
}
}
}
Function to write to file
private void writeToFile(string fileName)
{
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fileName);
foreach (var item in listBox.Items)
{
SaveFile.WriteLine(item.ToString());
}
}
Well you didn't specify the error, but my guess is that it isn't working because you didn't close the StreamWriter.
using (System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fileName))
{
foreach (var item in listBox.Items)
SaveFile.WriteLine(item.ToString());
}
Or you can just call SaveFile.Close() instead of using
Related
So I have a combo box that contains a list of trainees that is imported from a textfile (each trainee occupies a line in the textfile) and I have 3 buttons, add (adds a new trainee to the file and combobox), delete(Supposed to delete the specific line in the file containing the combobox selected item) and a modify button (supposed to overwrite a new trainee in the file at the same line that contains the combobox selected item), my add button works fine, idk how to modify or delete lines in a file.
I have no idea how to work this around as I'm new to working with files
here's my code
private void form1_Load(object sender, EventArgs e)
{
FileStream fs = new FileStream("trainee.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
while ((line = r.ReadLine()) != null)
{
comboBox1.Items.Add(line);
}
}
fs.Close();
}
private void deleteButton_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Choose a trainee to delete.", "Error !");
}
else
{
string selection = comboBox1.SelectedItem.ToString();
FileStream fs = new FileStream("stagiaire.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
while ((line = r.ReadLine()) == selection)
{
}
}
fs.Close();
private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Choose a trainee to modify.", "Error !");
}
else
{
string selection = comboBox1.SelectedItem.ToString();
FileStream fs = new FileStream("trainee.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
if ((line = r.ReadLine()) == selection)
{
Trainee stg = new Trainee();
stg.name = textBox1.Text;
stg.nickname = textBox2.Text;
stg.training_days = int.Parse(textBox3.Text);
addtrainee(stg);
comboBox1.Items.Add(stg);
}
}
fs.Close();
}
You may be working too hard, the List you have is working for you here. Whenever you need to output it, just write the whole list. When you need to manipulate the entries in it (elements), use the collection methods like Find, Contains, Add, Remove, others see (https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.7.2#methods)
You can shortcut you file access too, use the framework:
var fileLines = File.ReadLines("c:/temp/yourfile.txt");
No using and StreamReader/Writer needed, depending on your environment too I guess.
So you have your input as string and List<string> so you could do if (lines.Contains(testString)) for example.
Can provide more sample code if it helps.
I am new to this so bear with me.
I am trying to create an application that can open a file, load it and then populate the data into a table.
I have managed to hardcode it to the test file I wanted but now need to be able to open any file of the same extension.
The code I have so far is included.
Appreciate if someone could point me in the right direction :)
Thanks, Jo
OpenFileDialog ofd = new OpenFileDialog();
private void Button3_Click(object sender, EventArgs e)
{
ofd.Filter = "evtx|*.evtx"; //Only allows evtx file types to be seen and opened
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
}
private void loadFileButton_Click(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("Level");
dt.Columns.Add("Logname");
dt.Columns.Add("Event ID");
dt.Columns.Add("Date and Time");
using (var reader = new EventLogReader(#"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
EventRecord record;
while ((record = reader.ReadEvent()) != null)
{
using (record)
{
dt.Rows.Add(record.Level, record.LogName, record.RecordId, record.TimeCreated.Value.ToString("dd/MM/yyyy tt:hh:mm:ss"));
}
}
}
tblLogViewer.DataSource = dt;
}
If I understand what your issue is, you are prompting for a file in Button3_Click() with...
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
...but then in loadFileButton_Click() you are using a different path to construct an EventLogReader...
using (var reader = new EventLogReader(#"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
You are already saving the selected file's path to fileNameTextBox.Text, so just pass that property to the EventLogReader constructor instead...
using (var reader = new EventLogReader(fileNameTextBox.Text, PathType.FilePath))
{
Note that loadFileButton_Click assumes that ofd has previously been displayed and accepted (not canceled). Without knowing what your different buttons are, it might be better to create and use your EventLogReader immediately after successfully prompting for an input file...
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
using (var reader = new EventLogReader(ofd.FileName, PathType.FilePath))
{
// Use reader...
}
}
UI for browsing data
Im lookig for a way to save and open multiple entries of data from the text boxes onto a .txt file. By "multiple entries" I mean having a kind of database of (in this instance) members of a certain team, without the use of LINQ. So for example having Messi and his data as the first entry, then when I press "Next", the second player would appear along with their data.
Currently I am using the SaveFileDialog and OpenFileDialog method to save and open entries, however it only saves a single record.
private void menu_save_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == true)
{
using (StreamWriter write = new StreamWriter(File.Create(sfd.FileName)))
{
write.WriteLine(tbox_name.Text);
write.WriteLine(tbox_dob.Text);
write.WriteLine(tbox_number.Text);
write.WriteLine(tbox_nationality.Text);
write.WriteLine(tbox_height.Text);
write.WriteLine(tbox_weight.Text);
write.WriteLine(tbox_position.Text);
write.Close();
write.Dispose();
}
}
}
private void menu_open_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == true)
{
using (StreamReader read = new StreamReader(File.OpenRead(ofd.FileName)))
{
tbox_name.Text = read.ReadLine();
tbox_dob.Text = read.ReadLine();
tbox_number.Text = read.ReadLine();
tbox_nationality.Text = read.ReadLine();
tbox_height.Text = read.ReadLine();
tbox_weight.Text = read.ReadLine();
tbox_position.Text = read.ReadLine();
read.Close();
read.Dispose();
}
}
}
.txt file after saving data
I would like the application to be able to save, for example, 11 entries (players) on a single .txt file and be able to go through the "database" with the 'Next' and 'Previous' buttons. I would also like to have an option to sort the players in an alphabetical order. Any help would be much appreciated as Im new to WPF and havent quite gotten my head around it yet.
File.Create overwrites existing file (all previous data gets lost). Use File.AppendAllLines method:
private void menu_save_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == true)
{
File.AppendAllLines(sfd.FileName, new string []
{
tbox_name.Text,
tbox_dob.Text,
tbox_number.Text,
tbox_nationality.Text,
tbox_height.Text,
tbox_weight.Text,
tbox_position.Text,
});
}
}
similarly to read all data use File.ReadAllLines method, but you will have to separate lines into groups after that:
string[] lines;
int index;
private void menu_open_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == true)
{
lines = File.ReadAllLines(ofd.FileName);
index = 0;
Display(index);
}
}
private void Display(int number)
{
int i = number * 7; // 7 is a number of values per item
tbox_name.Text = lines[i];
tbox_dob.Text = lines[i+1];
tbox_number.Text = lines[i+2];
tbox_nationality.Text = lines[i+3];
tbox_height.Text = lines[i+4];
tbox_weight.Text = lines[i+5];
tbox_position.Text = lines[i+6];
}
to display next, do index++; Display(index);
to display previous, do index--; Display(index);
I am creating a text editor and i am stuck on the SaveFileDialog window opening
and asking to overwrite the current file open.
I have seen all the similar questions asked like this on SO but none have been able to help me. I have even tried the code from this question: "Saving file without dialog" Saving file without dialog
I got stuck on my program having a problem with FileName.
Here is the code i have currently
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(save.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
}
}
So my question is how can i modify my code so that i can save a file currently open without having the SaveFileDialog box opening everytime?
I do understand that it has something to do with the fact that i'm calling .ShowDialog but i don't know how to modify it.
When opening the file, save the FileName in a form-level variable or property.
Now while saving the file, you can use this FileName instead of getting it from a FileOpenDialog.
First declare a variable to hold filename at form level
// declare at form level
private string FileName = string.Empty;
When opening a file, save the FileName in this variable
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
// save the opened FileName in our variable
this.FileName = open.FileName;
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
And when doing SaveAs operation, update this variable
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
// save the new FileName in our variable
this.FileName = saving.FileName;
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
The save function can then be modified like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.FileName))
{
// call SaveAs
saveAsToolStripMenuItem_Click(sender, e);
} else {
// we already have the filename. we overwrite that file.
StreamWriter writer = new StreamWriter(this.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
In the New (and Close) function, you should clear this variable
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear the FileName
this.FileName = string.Empty;
richTextBox1.Clear();
}
Create a new string variable in your class for example
string filename = string.empty
and then
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(filename)) {
//Show Save filedialog
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
filename = save.FileName;
}
}
StreamWriter writer = new StreamWriter(filename);
writer.Write(richTextBox1.Text);
writer.Close();
}
The SaveFileDialog now only opens if fileName is null or empty
You will have to store the fact that you have already saved the file, e.g. by storing the file name in a member variable of the Form class you have. Then use an if to check whether you have already saved your file or not, and then either display the SaveFileDialog using ShowDialog() (in case you haven't) or don't and continue to save to the already defined file name (stored in your member variable).
Give it a try, do the following:
Define a string member variable, call it _fileName (private string _fileName; in your class)
In your saveToolStripMenuItem_Click method, check if it's null (if (null == _fileName))
If it is null, continue as before (show dialog), and after getting the file name, store it in your member variable
Refactor your file writing code so that you either get the file name from the file dialog (like before), or from your member variable _fileName
Have fun, C# is a great language to program in.
First, extract method from saveAsToolStripMenuItem_Click: what if you want add up a popup menu, speed button? Then just implement
public partial class Form1: Form {
// File name to save text to
private String m_FileName = "";
private Boolean SaveText(Boolean showDialog) {
// If file name is not assigned or dialog explictly required
if (String.IsNullOrEmpty(m_FileName) || showDialog) {
// Wrap IDisposable into using
using (SaveFileDialog dlg = new SaveFileDialog()) {
dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
dlg.Title = "Save File";
dlg.FileName = m_FileName;
if (dlg.ShowDialog() != DialogResult.OK)
return false;
m_FileName = dlg.FileName;
}
}
File.WriteAllText(m_FileName, richTextBox1.Text);
this.Text = Path.GetFileNameWithoutExtension(m_FileName);
return true;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
// SaveAs: always show the dialog
SaveText(true);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
// Save: show the dialog when required only
SaveText(false);
}
...
}
I'm trying to save ListBox items in text file.
The Items I have added from properties:
My code is:
private void button1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter st = new StreamWriter(S))
foreach (string aa in listBox1.Items)
st.WriteLine(listBox1.Items);
}
}
The output in text file is: System.Windows.Forms.ListBox+ObjectCollection
As #davidsbro mentioned, you want aa to be in the st.Writeline as that is the actual string. listBox1.Items gives a class which Writeline can't handle as it doesn't know what you would want from Items. So it outputs the name which is the result you got. If you want all the properties and other information about that Items class you would have to serialize it and write to the file.
Just use the aa into writeLine
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
{
using (StreamWriter st = new StreamWriter(S))
{
foreach (var aa in listBox1.Items)
st.WriteLine(aa.ToString());
}
}
}