I have a ListView that loads a .txt file with some phone numbers and when i click the delete button it will delete the selected line from the ListView. When I click the button to delete, the button delete the line but doesn't save the file with the updated list.I'll provide more information if asked.
Thank you!!
here is the delete button
public void Deletar_lista()
{
var caminho = Directory.GetCurrentDirectory();
caminho += "\\telefones.txt";
listView1.Items.RemoveAt(listView1.SelectedIndices[0]);
}
I only have a little bit of code to go on here, but it appears that you are only deleting the item from the ListView.
Your application will not automatically know that you want it to save the updated content of the ListView to the file.
To do this, try the following:
string[] lines = System.IO.File.ReadAllLines(caminho);
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(caminho))
{
foreach (string line in lines)
{
if (!line.Contains(listView1.SelectedIndices[0].ToString()))
{
writer.WriteLine(line);
}
}
}
This reads all the lines from the file, and if the selected line equals your deleted entry, it will not write it to the file.
I manage to make it work. Here is what I done:
int ll_count = -1;
var caminho = Directory.GetCurrentDirectory();
caminho += "\\telefones.txt";
if (MessageBox.Show("Deseja mesmo deletar o numero?", "Usuario", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
string[] lines = File.ReadAllLines(caminho);
using (StreamWriter writer = new StreamWriter(caminho))
{
foreach (string line in lines)
{
ll_count++;
if (ll_count != listView1.SelectedIndices[0])
{
writer.WriteLine(line);
}
}
}
listView1.Items.RemoveAt(listView1.SelectedIndices[0]);
Related
I am working on a program for personal use that will automatically sort a grocery list (from file) into a particular order. I want the program to open the file, read each line, and determine if each line contains certain words. For example, a line could contain "chicken breasts," and the program would just recognize that it contained "chicken." The idea is to have the program automatically order my list so that I'm not running back and forth getting items when I go to the store. Currently the external file line must have the exact text "chicken" for the program to recognize it ("chicken breasts" will not be recognized). Here is the section that I believe is giving me trouble:
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
}
Groceries is an array with each element being a line from the file (I think I created it correctly). Below is the entire code:
private void btnImport_Click(object sender, EventArgs e)
{
//Grocery items
string chicken;
//StreamReader variable
StreamReader readFile;
string filePath;
//Counter variable
int index = 0;
//Display open file dialog box
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Set filepath as a variable
filePath = openFileDialog1.FileName;
// Assign the file as a variable
readFile = File.OpenText(filePath);
//Count lines in file and create array
int lineCount = File.ReadLines(filePath).Count();
string[] groceries = new string[lineCount];
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
index++;
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
//Display items in label
lstItems.Items.Add(chicken);
}
}
//Close file
readFile.Close();
}
}
When the program is run, it will add "Chicken" to the listbox the same number of times as the number of lines in the file, even though only one line actually contains "chicken." My question is: How can I make it pick out the keyword from a longer line of text, and why is it adding the item more than once? Thanks!
Edit
(Sorry I don't know how to attach a file here)
I am currently importing a .txt file with the following data:
chicken
fish
Frosted Flakes cereal
pork tenderloin
ground beef
First, you need to remove the redundant openFileDialog1.ShowDialog();. And access the elements in groceries by index. Then add additional conditions to exclude rows that contain "chicken breasts". Note that index++ is executed after the if statement.
// define a varibale
bool chickenadded = false;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// remove the redundant ShowDialog
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// code omitted ...
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
// check here
if (groceries[index].Contains("chicken") && !chickenadded /*&& !groceries[index].Contains("chicken breasts")*/)
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
// set to true
chickenadded = true;
// another way is not define boolean, just use "break"
break;
}
// reset index here
index++;
}
Disregarding any other problem or what the overall goal of the application is. You forgot to look at the actual line
if (groceries[index].Contains("chicken"))
It's worth a note that you should likely be using File.ReadLines or File.ReadAllLines instead. As it gives you a collection or enumerable to work with
So I want to make some sort of management system or list maker. And I want the data to be stored in a text file. Here's what I have.
So when you click then exit button on the form
private void btnExit_Click(object sender, EventArgs e)
{
if (!File.Exists("paste.txt"))
{
}
else if (File.Exists("paste.txt"))
{
File.Delete("paste.txt");
StreamWriter file = new StreamWriter("paste.txt");
string text = listBox1.Text;
file.Write(text);
file.Close();
}
this.Close();
}
So I want it to save all the text in the textbox to a text file. How could I do this? Right now when I click the exit button the file stays blank.
You can use File.WriteAllText. This will overwrite what's in it at all times, so there's no point in deleting it first if that's what you want.
var path = "paste.txt";
var listBoxText = "";
foreach(var item in listBox1.Items)
{
listBoxText += item.ToString() + "\n";
}
if (File.Exists(path))
{
File.WriteAllText(path, listBoxText, Encoding.UTF8);
}
Not sure what your requirements are OP, but if you also want to create the File if doesn't exist, you could do:
var file = new FileInfo(path);
file.Directory.Create(); // will do nothing if it already exists
File.WriteAllText(path, listBox1.Text, Encoding.UTF8);
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.8
Here is the pretty way of doing it
Lets say you have an item object
public class ListItem
{
public string Value { get; set; }
public string Description { get; set; }
public string DisplayValue
{
get
{
return $"[{Value}] - {Description}";
}
}
}
You see, I provided an object that could be like that, more complex object, but could be just a string.
When you add objects you create a list and do something like this
var itemList = new List<ListItem>();
// add items
myLst.DisplayMember = "DisplayValue";
myLst.ValueMember = "Value";
myLst.DataSourse = itemList;
In this case you can get the list of "any property" like this (System.Linq)
string[] fileLines =
((List<ListItem>)myLst.DataSourse).Select(itm => itm.Value).ToArray();
Or, if your items are simple strings
string[] fileLines = (from itm in myLst.Items select itm).ToArray();
And then use your file logic to simply in the end call
File.WriteAllLines(path, fileLines);
What I like about this approach is that no explicit loops needs and item can be a more complex item that can have a bunch of properties beyond a simple string description/value in one.
Im a beginner programmer and im stuck on this project for my internship
Lets say i have hello.txt in folder1 Listbox1 takes it from folder1 and put it in the listbox.
listbox2 does the same thing with folder2 except with a diffrent extension
After for example i have created hello.DOCX i need hello.txt to be removed from listbox1 but not from folder1
i hope this is clear
this is my code to get files from folders
private void LBNietGedaan_Loaded(object sender, RoutedEventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\nour\Desktop\Niet gedaan");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
LB1.Items.Add(file.Name);
}
}
private void LBGedaan_Loaded(object sender, RoutedEventArgs e)
{
//zet files van een folder in de listbox
DirectoryInfo dinfo = new
DirectoryInfo(#"C:\Users\nour\Desktop\Gedaan");
FileInfo[] Files = dinfo.GetFiles("*.DOCX");
foreach (FileInfo file in Files)
{
LB2.Items.Add(file.Name);
}
}
Can't you just make a property with an ObservableCollection or so and then bind the listbox to it? Then you can simply clear it and the listbox will be empty again.
Binding ObservableCollection to WPF ListBox
This is pseudo, so it might need some adjusting, but basically you can but it in a button click, or place it in your first method after you load the list, adjust the variables to match yours.
List<string> one = new List<string>();
foreach (String string1 in LB1.Items)
{
one.Add(string1);
}
List<string> two = new List<string>();
foreach (String string2 in LB2.Items)
{
two.Add(string2);
}
foreach (String string1 in one)
{
foreach (String string2 in two)
{
string cat1 = string1.Substring(0, string1.Length - 4);
string cat2 = string2.Substring(0, string2.Length - 5);
if (cat1.Equals(cat2))
{
LB1.Items.Remove(string1);
// if you want to stop after the first match, break;
// else remove break to find all matches;
break;
}
}
}
Basically this will search the items in listbox1's Items, and remove any file called "yourtarget.txt". I think should send you in the right direction. If you need more let me know!
I have been looking around for hours on how to do this, I think the best idea is to come up with a for each loop and then pass that through into the Stream Writer.
I've tried multiple different ways, and I think maybe I'm just not good enough to see my error, if anyone would be able to help that's be great.
Currently the file gets created and the only output I get for it is "System.Windows.Forms.ListBox+ObjectCollection" on the first line, which suggests to me that I'm not passing the values out properly.
Here's the code :
private void btnSave_Click(object sender, EventArgs e)
{
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
myOutputStream.WriteLine(lstBox.Items);
myOutputStream.Close();
//foreach (object item in lstBox.Items)
//string listString = lstBox.SelectedItem.ToString();
//StreamWriter streamBox = File.CreateText(#"testfile.csv");
//streamBox.Write(listString);
//streamBox.Close();
//if (SaveFileDialog.ShowDialog() == DialogResult.OK)
//{
// System.IO.StreamWriter streamBox = new System.IO.StreamWriter(SaveFileDialog);
// foreach (object item in lstBox.Items)
// streamBox.WriteLine(item.ToString());
// streamBox.Close();
//}
}
All the commented out parts are things I've tried in the past. But right now, I think the simplest way was the top three lines.
Thanks for your input.
You are writing out listBox.Items, which is an ListBoxObjectCollection. You need a foreach loop to write each item:
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
foreach (var item in lstBox.Items)
{
myOutputStream.WriteLine(item.ToString());
}
myOutputStream.Close();
Also note that you can use a using block here:
using (StreamWriter myOutputStream = new StreamWriter("Myfile.csv"))
{
foreach (var item in lstBox.Items)
{
myOutputStream.WriteLine(item.ToString());
}
}
First, what's in the ListBox? If the items in the list box are just string items, then you could do the following:
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
foreach (string item in lstBox.Items) {
myOutputStream.WriteLine(item);
}
myOutputStream.Close();
I have a Windows application that takes the data in the textboxes and writes them into a randomly generated text file, kinda keeping logs. Then there is this listbox that lists all these separate log files. The thing I want to do is to have another listbox display the file info of the selected one, the 2nd, 7th, 12th, ..., (2+5n)th lines of the text files that is selected after the button 'list info' is clicked. How is it possible to do this?
My code to update the first listbox is:
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\Ece\Documents\Testings");
// What type of file do we want?...
FileInfo[] Files = dinfo.GetFiles("*.txt");
// Iterate through each file, displaying only the name inside the listbox...
foreach (FileInfo file in Files)
{
listBox1.Items.Add(file.Name + " " +file.CreationTime);
}
}
On the SelectedIndexChanged event you want to get the selected item. I wouldn't suggest showing the second part in another list box, but i'm sure you can work out how from the example below if you require it. I would personally have a richTextBox, and just read the file to there:
//Get the FileInfo from the ListBox Selected Item
FileInfo SelectedFileInfo = (FileInfo) listBox.SelectedItem;
//Open a stream to read the file
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
//Read the file to a string
string FileBuffer = FileRead.ReadToEnd();
//set the rich text boxes text to be the file
richTextBox.Text = FileBuffer;
//Close the stream so the file becomes free!
FileRead.Close();
Or if you are persistant to sticking with the ListBox then:
//Get the FileInfo from the ListBox Selected Item
FileInfo SelectedFileInfo = (FileInfo) listBox.SelectedItem;
//Open a stream to read the file
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
string CurrentLine = "";
int LineCount = 0;
//While it is not the end of the file
while(FileRead.Peek() != -1)
{
//Read a line
CurrentLine = FileRead.ReadLine();
//Keep track of the line count
LineCount++;
//if the line count fits your condition of 5n + 2
if(LineCount % 5 == 2)
{
//add it to the second list box
listBox2.Items.Add(CurrentLine);
}
}
//Close the stream so the file becomes free!
FileRead.Close();