how to save listbox items in text file? - c#

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

Related

How do I delete or modify a line in a text file if it matches the string in my combo box C#

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.

Saving and reading a file into a data table - C#

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...
}
}

Save ListBox items to file

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

How to save dynamic ListBox items to a text file WP8

I have a ListBox that on run is empty, but the items (Buttons ) are added dynamically. I have a text file in my Solution favorites.txt and I need that ListBox.Items name to be save for future show.
In XAML I have 2 Buttons that are placed in different ListBoxes in Line:
<ListBox x:Name="mainlist" >
<Button x:Name="but1" / >
</ListBox>
<ListBox x:Name="favlist" >
<Button x:Name="fav1" Click="Button_Click_2" Tag="but1" />
</ListBox>
Next in .cs I search for but1 by fav1.Tag and add it to Favorites List Box :
private void Button_Click_2(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
button.Opacity = 0;
button.Click -= Button_Click_2;
object item = mainlist.FindName(button.Tag.ToString());
if (item is Button)
{
Button findedBut = (Button)item;
Button newbut = new Button();
newbut.Name = findedBut.Name;
//add this button to other ListBox called Favorites that is empty
Favorites.Items.Add(newbut);
}
}
And I want to save Favorite Items for future launching because if I close applications the ListBox Favorites is empty again.
Something Like a function:
void updateFavs()
{
// this is not working ((
using (FileStream S = File.Open((new Uri(#"favorites.txt", UriKind.Relative)), FileMode.Open))
{
using (StreamWriter st = new StreamWriter(S))
{
foreach (var aa in Favorites.Items)
st.WriteLine(aa.ToString());
}
}
}
and call this functions every time before Application.Current.Terminate();
Or maybe there is other ways that I don't know... maybe Isolated Storage? Like here:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspx
I think that you have to use the Isolated Storage:
\\Create file and save data
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file.txt", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(1);
writer.WriteLine("Hello");
}
}
\\To read from the file
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file.txt", FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
{
using (StreamReader reader = new StreamReader(stream))
{
int number = Convert.ToInt32(reader.ReadLine());
string text = reader.ReadLine();
}
}

Read xls/xlsx and display on screen

I'm using 'ExcelDataReader' to read in an Excel file, I want to display the file on screen.
protected void Page_Load(object sender, EventArgs e)
{
string filePath = #"C:\WORK\BoireannSVN\trunk\VS\CRCConnect\Spreadsheet\Spreadsheet.xlsx";
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
while (excelReader.Read())
{
Label x = new Label();
x.Text = result.Tables[0].Rows[0].ItemArray[0].ToString();
uploadExcel.Controls.Add(x);
excelReader.GetInt32(0);
}
excelReader.Close();
}
I've added in the
Label x = new Label();
x.Text = result.Tables[0].Rows[0].ItemArray[0].ToString();
Attempting to get the excel sheet to display on screen, although I'm having no luck with this. I think it is something like
table1.Columns.Add;
table1.Rows.Add;
but can't seem to get it going, any help much appreciated.
I was in a similar situation I did the following:
var rows = results.Tables[0].AsEnumerable();
Then you can iterate and select the value for columns:
foreach (var dataRow in rows)
{
Console.WriteLine(dataRow[0]);
//or
Console.WriteLine(dataRow["ColumnName"]);
}

Categories

Resources