简体   繁体   中英

How can I put listbox text/items into a text file?

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://docs.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM