Windows form app saving to .txt method - c#

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

Related

Saving added items in a combobox to a file

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.

removing file extension and location from list box

Im making a mp3 player in c# and im using a autoload function and it works perfectly to load and play, but the "problem" in in the list box where the .mp3 files are displayed. it shows the file directory and file extension like this:
C:\Users\Felix\Documents\songs_here\list_1\Admiral P - Engle.mp3
and insteed of that i would like it to show:
Admiral P - Engel
is this possible and how to i do it? the file load code is:
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
listBox1.Items.Add(file);
}
PopulateListBox1(dir1);
Thanks in advance!!
You can use Path.GetFileNameWithoutExtension.
Path.GetFileNameWithoutExtension Method (String)
Returns the file name of the specified path string without the extension.
For example:
Path.GetFileNameWithoutExtension("C:\Users\...\songs_here\list_1\Admiral P - Engle.mp3");
Would return:
Admiral P - Engle
Update:
I'm assuming from your comment that you want to display the file name but still have a reference to the path to the file to pass to your player.
You'll need to create your own class to hold the mp3 file name and path like this:
public class MusicFile
{
public string Path;
public string FileName;
public override string ToString()
{
return FileName;
}
}
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
{
var music = new MusicFile
{
Path = file,
FileName = Path.GetFileNameWithoutExtension(file)
};
listBox1.Items.Add(music);
}
}
This shows how to loop through each item and get the path, but you could also use events such as SelectedIndexChanged depending on your needs.
foreach (var item in listBox1.Items)
{
var filepath = ((MusicFile)item).Path; // Shows the full path, pass this to the player
}
Using Linq one line code
private void PopulateListBox1(string folder)
{
listBox1.DataSource =Directory.GetFiles(folder).Select(x => Path.GetFileNameWithoutExtension(x)).ToList();
}
as the file naming pattern is the same, first you might want to check file extension with a string split on dot character on every file entry, then for each file if it is mp3 extension , split an pop the last word

C# Best Way to Save Text Files into Objects

I have a group of delimited text files I need to read, create a class and objects, and store members inside. I am a beginner that's just looking to be pointed in the right direction. Any help would be appreciated greatly. Thank you very much.
I made a class with objects with:
public string left;
public string right;
and my form code :
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
textBox2.Text = sr.ReadToEnd();
// sr.Close();
}
private void button3_Click(object sender, EventArgs e)
{
string[] split1 = textBox2.Text.Split(';');
foreach (string segment in split1)
{
//split sub-segment
string[] split2 = segment.Split(':');
//check if it's valid
if (split2.Count().Equals(2))
{
id textfile = new id();
textfile.left += // ????
id textfile1 = new id();
textfile.right += // ????
Generally, it's much preferable to use JSON or XML to save data to text files rather than delimited text or custom formats. That's because good JSON and XML support is available in my languages and it's easy to work with.
public class MyCustomClass //this class will hold your data
{
public string Left {get; set;}
public string Right {get;set;}
}
MyCustomClass mcc=new MyCustomClass(); //create an instance of your class
mcc.Left="yes"; //set some properties
mcc.Right="nope";
string json=JsonConvert.SerializeObject(mcc); //convert to JSON string
File.WriteAllText("mcc.txt",json); //save to file
//later on, when you want to read it back from the file
string json=File.ReadAllText("mcc.text"); //read from file into a string
MyCustomClass mcc=JsonConvert.DeserializeObject<MyCustomClass>(json); //convert the string back to an instance of MyCustomClass
Above, we use Json.NET which is a library available for the .NET Framework (available on NuGet). We use it to convert our object to a string (serialize) and then later on to convert it back to an object (deserialize). Note that in order to use the JsonConvert class, you'll need the Json.NET references and to add a using statement at the top of your class using Newtonsoft.Json;.
What you're looking for is serialization. When you have a known structure (like your class with string left and string right), you want to write that structure out to a text file. Then later, you want to read that information back in and automatically populate the class with each of the values.
As mason pointed out, JSON is fairly easy to setup. You create the class structure that you want, and tell JSON to save that out to a specified file (via SerializeObject).
Since .NET allows for reflection, JSON is able to turn the text file back into the contents of a class without you having to manually 'myClass.left = [some_value_from_json]'.
Personally, I'd go with JSON or XML, since naming your blocks of data means it is both more readable, and that your parser is able to handle someone rearranging the data (it doesn't matter if the file defines left before it defines right). If you rearranged a .CSV file, then you get data corruption.
Reading delimited files is common and there are many approaches to the subject. Personally I use a streamReader to read in the file and split it on the delimiter:
Foo foo = new Foo(); // custom class
string file = "export.CSV";
if (System.IO.File.Exists(file))
{
// Do work
using (var reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
// split on the delimeter
var readLine = reader.ReadLine();
if (readLine == null) continue;
var lines = readLine.Split(new[] { ',' });
foreach (string s in lines)
{
// do something with the data from the line
}
// alternatively, you could specify your objects if your files
// layout never changes. Just be careful to catch the exceptions!
foo.bar = lines[0];
foo.baz = lines[1];
}
}
}

Outputting all text file titles to a textbox on Windows Form

Getting a bit stuck on a piece of code I'm trying to write and was hoping for a helping hand if anyone knows where I'm going wrong!
I have a simple Windows Form where I have a folder browser. The user will browse to a folder and any sub-folders within will then be searched for a text file that has the word "Passed" in the title (not the body of the text file itself). There will be files with "Passed" in from many different folders, and I want the functionality of the app to search through all sub-folders and return the all the files that have this in their name.
At present I have the following code:
private void searchButton_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please enter a path");
}
else
{
string[] allFiles = Directory.GetFiles(textBox1.Text, "*Passed*.*", SearchOption.AllDirectories);
string name = resultsText.Text;
foreach(string file in allFiles)
{
if (file.Contains("Passed"))
{
resultsText.Text = file;
}
}
}
}
However, in the resultsText texbox, it only returns 1 value. There are multiple files with "Passed" in their title and I would like to print them all to this textbox. Does anyone know where I may be going wrong and why I am only getting one file rather than all of them?
Also, this method seems to return the whole file path e.g.)
C:\Program Files\Test\abc\PassedTests.txt - does anyone know how I can trim the full path so it just returns the file name and extension?
Any help is greatly appreciated!
You need to append the text. At the moment, you're overwriting the previous value by using resultsText.Text = file;.
if (file.Contains("Passed"))
{
resultsText.AppendText(file);
}
What may be more performant would to use build your string using a StringBuilder and then assign that to the TextBox.
StringBuilder sb = new StringBuilder();
foreach(string file in allFiles)
{
if (file.Contains("Passed"))
{
sb.Append(file);
}
}
resultsText.Text = sb.ToString();
You have to change 1 line of code:
resultsText.Text = file;
To this:
resultsText.Text += file;
The + will append the text and not overwrite it.
this is the answer for your second question.
try this to get only the file name
Path.GetFileName(filepath)

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