Saving added items in a combobox to a file - c#

I am having issues writing to a file in a C# program for class.
My program loads a .txt file to a combo box, which has 3 state options. Users can add up to 5 additional states from a selected list. On Exit, the program saves the added information back to the .txt file if the user chooses Yes.
My issue is that the code below is adding the default states back into the list. Should I be using an If statement under the foreach statement, or is there a way to write it so that only the User-added states are added to my .txt file and not all values all over again?
private void saveMyFile()
{
try
{
StreamWriter outputFile;
outputFile = File.AppendText("states.txt");
foreach (var cbitem in statesComboBox.Items)
{
outputFile.WriteLine(cbitem);
}
outputFile.Close();
MessageBox.Show("Your information has been saved. Closing program.");
}
catch
{
MessageBox.Show("Data could not be written to file");
}
}

There are several things you can do to achieve this.
If the order of the items in the combobox is fixed, you can skip the first x items when saving:
private int ExistingStates = 3; // You can later change this number when
// loading the items.
private void saveMyFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("states.txt");
foreach (var cbItem in statesComboBox.Items.Cast<string>().Skip(ExistingStates))
{
outputFile.WriteLine(cbItem);
}
outputFile.Close();
}
You can have an array of the existing items so you can check if the item being saved already exists:
private string[] ExistingStates = {"state1", "state2"}; // Add items to the array
// after loading them.
private void saveMyFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("states.txt");
foreach (var cbItem in statesComboBox.Items)
{
if (!ExistingStates.Contains(cbItem))
outputFile.WriteLine(cbItem);
}
outputFile.Close();
}
Another option is to overwrite the existing items by replacing the AppendText method with CreateText:
private void saveMyFile()
{
StreamWriter outputFile;
outputFile = File.CreateText("states.txt");
foreach (var cbItem in statesComboBox.Items)
{
outputFile.WriteLine(cbItem);
}
outputFile.Close();
}
Or you can replace the whole method with one simple line (using the WriteAllLines method):
File.WriteAllLines("states.txt", statesComboBox.Items.Cast<string>());
Hope that helps.

Related

Method for "adding" new data to current open file C#

I am writing a program where I have 2 listboxes with the same data but the one listbox items are update with the student name and their TOTAL score and the other with the student name and each individual judge score next to the student name. Everything is going good so far but now I am stuck... I have two methods Save() and SaveAs() where Save() automatically writes data to "FormData.bin" and SaveAs() lets the user enter their own file name.
Is it possible to re-write the Save() method so that when I click save it saves the current data to the file that is open like in MS Word when you are typing in document and just click save to add new typed data to current file. Here is my Save() method I wrote.
public void SaveEntry()
{
int itemsCount = Math.Min(lstbxStudents.Items.Count, lstbxStudentScore.Items.Count);
saveFileDialog1.InitialDirectory = Application.StartupPath;
saveFileDialog1.FileName = "FormData.bin";
{
try
{
using (FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create))
using (BinaryWriter Save = new BinaryWriter(fs))
{
Save.Write(cmbbxAge.Text);
Save.Write(cmbbxBelt.Text);
Save.Write(cmbbxCategorie.Text);
Save.Write(cmbbxGender.Text);
Save.Write(cmbbxGup.Text);
Save.Write(txtJudge1.Text);
Save.Write(txtJudge2.Text);
Save.Write(txtJudge3.Text);
Save.Write(txtJudge4.Text);
Save.Write(txtJudge5.Text);
Save.Write(txtOperator.Text);
Save.Write(txtPos1.Text);
Save.Write(txtPos2.Text);
Save.Write(txtPos3.Text);
Save.Write(txtPos4.Text);
Save.Write(txtPos5.Text);
for (int i = 0; i < itemsCount; i++)
{
Save.Write(lstbxStudents.Items[i].ToString());
Save.Write(lstbxStudentScore.Items[i].ToString());
}
Save.Close();
fs.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message, "CTSD Forms");
}
}
}
Thank you in advance
Here is image of Form
Window Form
If I understood correctly what you are trying to achieve is to append text rather than overwrite it. Take a look upon the StreamWriter class that also allows to specify if you want to append the data or not when constructing the instance. It also allows to create/append to the file directly, without the need of a Stream.
Also, consider using proper names for variables:
Save is an action, not an object. writer would be better.
By using Write in the way you showed in your code, you will end with all the texts appended with no separators. You should consider using WriteLine functions.
[edit upon clarifications]
SaveEntry should take a parameter to specify if save is done as SaveAs or Save. First save should always be a SaveAs. Also filename should be saved in the context (your form class, but it is better to have a "view model")
private String _currentFileName;
public void SaveEntry(bool saveAs)
{
if (saveAs || String.IsNullOrEmpty(_currentFileName))
{
saveFileDialog1.InitialDirectory = Application.StartupPath;
saveFileDialog1.FileName = "FormData.bin";
var result = saveFileDialog1.ShowDialog();
// TODO: handle user cancellation
_currentFileName = saveFileDialog1.FileName;
}
using (var writer = new StreamWriter(_currentFileName))
{
// TODO: do stuff with your writer
}
}

Windows form app saving to .txt method

Hi I'm attempting a self project to write a shopping cart program that allows users to add, remove, drop(singular removal), delete(remove all), save (like a receipt), update(change added item data) and I'm having an issue with the saving currently.
I looked around on Stack overflow and found something that seems to almost work but I'm not sure what I'm doing wrong exactly... Method below
public void Save(string fileName)
{
System.IO.File.WriteAllText(#"C:\Users\barry\Desktop\GG\pewpew\receipt.txt", contents);
}
I'm not sure what exactly is supposed to replace "contents" I guess a description of my going about this will help understand.
File structure is a WFA with two added classes for functionality.
contents is the string you want to write on the txt file
contents is the data you want to write to the file i.e. the receipt contents. You will need to build the receipt up as a string and pass this in to WriteAllText
Rough example:
public void Save(string fileName)
{
var content = new StringBuilder();
foreach(var cartItem in shoppingCart)
{
content.AppendFormat("Item: {0}{1}", cartItem.Name, Environment.NewLine);
}
System.IO.File.WriteAllText(#"C:\Users\barry\Desktop\GG\pewpew\receipt.txt", contents.ToString());
}
Contents is the text you want to save to the file.
So:
public void Save(string fileName, contents)
{
System.IO.File.WriteAllText(filename, contents);
}
Would give you a text file containing the text from the contents parameter. The file would be the name the was given for the filename parameter.
To get all of the items from the listbox, you could use:
var items = "";
foreach (var item in listBox1.SelectedItems)
{
items += item.ToString();
items += "\n";
}
Save(#"C:\my-file.txt", items);

C# Directory.GetFiles() only showing one file in the list?

I am trying to learn C#, I am starting with some simple stuff.
I am trying to create a simple program that will read all files in a directory which are .XLS extension. I seem to have it working partially, but it only reads the file it sees.
I thought the foreach statement would take care for this and list them all but it doesn't seem to work.
If anyone could put me in the right direction I would really appreciate it.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GetFiles();
}
private void GetFiles()
{
List<String> Myfiles = new List<string>();
string[] allFiles = System.IO.Directory
.GetFiles(#"C:\Users\Dave\Desktop\STUFF", "*.*");
if (allFiles.Length > 0)
{
try
{
foreach (string filename in allFiles)
{
this.richTextBox1.Text = filename.ToString();
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
Filter file for xls:
string[] allFiles = System.IO.Directory.GetFiles(#"C:\Users\Dave\Desktop\STUFF", "*.xls");
and update your try block code as :
try
{
this.richTextBox1.Text= string.Join(Environment.NewLine, allFiles);
//foreach (string filename in allFiles)
//{
// this.richTextBox1.Text = filename.ToString();
//}
}
I think it may be caused by this line:
this.richTextBox1.Text = filename.ToString();
You're essentially overwriting the text of the textbox each time, causing only the last filename being written to the richtextbox. You should be appending the filename string to the richTextBox rather than assigning.
from a quick look I think your issue is here:
this.richTextBox1.Text = filename.ToString();
you are assigning the text property with the last loop iteration rather than appending a new line for each file.
try to debug the for loop, do you have multiple iterations?
Because you want xls files, update this line:
string[] allFiles = System.IO.Directory.GetFiles(#"C:\Users\Dave\Desktop\STUFF", "*.xls");
You see probably one file in the edit box. Therefore, update the line:
this.richTextBox1.AppendText(filename + Environment.NewLine);

Read file from listbox

I have some code that will load full file names (ex.F:\logs\1234.log) into a listbox depending on the directory the user chooses. When the user selects one or more of the files and clicks the output button, I want the code to read through each selected file. Before, I was using a combobox and the code:
StreamReader sr = new StreamReader(comboBox1.Text);
This obviously does not work for listboxes. What is the simplest way to have the program read the user selected file(s) from the listbox?
To access all selected items in a ListBox you can use the SelectedItems property:
foreach (string value in listBox1.SelectedItems)
{
StreamReader sr = new StreamReader(value);
...
}
If you are choocing one file per time to open, then a solution would be as follows:
string[] files = Directory.GetFiles(#"C:\");
listBox1.Items.Clear();
listBox1.Items.AddRange(files);
Then, to get to the file path selected:
if (listBox1.SelectedIndex >= 0)
{ // if there is no selectedIndex, property listBox1.SelectedIndex == -1
string file = files[listBox1.SelectedIndex];
FileStream fs = new FileStream(file, FileMode.Open);
// ..
}
What you can do it to create a generic list, which will hold all the text from selected files:
void GetTextFromSelectedFiles()
{
List<string> selectedFilesContent = new List<string>();
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
selectedFilesContent.Add(ReadFileContent(listBox1.SelectedItems.ToString()));
}
//when the loop is done, the list<T> holds all the text from selected files!
}
private string ReadFileContent(string path)
{
return File.ReadAllText(path);
}
I think in your example when you explicitly said "as simple as possible" to read the file, would be best to use File.ReadAllText() method, better then using StreamReader class.
You should have been more clear in your original question... but if you need to read all the files:
var items = listBox.SelectedItems;
foreach (var item in items)
{
string fileName = listBox.GetItemText(item);
string fileContents = System.IO.File.ReadAllText(fileName);
//Do something with the file contents
}

C# Using Lists to read, write and search text file lines

I need to perform the following operations with a text file and a List:
Read all lines of text file (non delimited) into a string based list
Whilst the application is open I need to do the following:
Check for instances of a string in the List
Add new entries to the List
Remove all identical instances of a defined string from the List
Write the contents of the List back to the text file including any changes made as soon as they are made
Firstly, how do I read and write between Lists and text files?
Secondly, how do I search a List for a string?
Lastly, how do I safely remove an item out of a List without leaving gaps in the text file I write?
public void homework()
{
string filePath = #"E:\test.txt";
string stringToAdd = "test_new";
IList readLines = new List();
// Read the file line-wise into List
using(var streamReader = new StreamReader(filePath, Encoding.Default))
{
while(!streamReader.EndOfStream)
{
readLines.Add(streamReader.ReadLine());
}
}
// If list contains stringToAdd then remove all its instances from the list; otherwise add stringToAdd to the list
if (readLines.Contains(stringToAdd))
{
readLines.Remove(stringToAdd);
}
else
{
readLines.Add(stringToAdd);
}
// Write the modified list to the file
using (var streamWriter = new StreamWriter(filePath, false, Encoding.Default))
{
foreach(string line in readLines)
{
streamWriter.WriteLine(line);
}
}
}
Try to google before you post the question.
I'd start here:
Read from text file: http://dotnetperls.com/readline
List Actions
1. Removing from a list
2. Searching in a List
Write to a text file: http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx
I'll just share my idea...
using System.IO;
public void newMethod()
{
//get path of the textfile
string textToEdit = #"D:\textfile.txt";
//read all lines of text
List<string> allLines = File.ReadAllLines(textToEdit).ToList();
//from Devendra's answer
if (allLines.Contains(stringToAdd))
{
allLines.Remove(stringToAdd);
}
else
{
allLines.Add(stringToAdd);
}
//extra: get index and edit
int i = allLines.FindIndex(stringToEdit => stringToEdit.Contains("need to edit")) ;
allLines[i] = "edit";
//save all lines
File.WriteAllLines(textToEdit, allLines.ToArray());
}

Categories

Resources