hi, I now face some problems in saving the content of the listBox to the exist text file. i need to append the content to the text file and canot overwrite the content in the text file.Who can help me..?

FileStream fs2 = new FileStream(@"C:\Users\Fish\Desktop\fyp-coding\Combine.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);//create text file 
            StreamWriter sw2 = new StreamWriter(fs2, Encoding.Default);
            foreach (string item2 in ListItemCom2.Items)
            { 
                 sw2.WriteLine(item2.ToString().Trim());// write to the text file      
            }
              

            sw2.Flush();
            sw2.Close();
            fs2.Close()

Dani AI

Generated

Two simple choices depending on the goal: replace the file with exactly the current ListBox contents, or append but avoid writing duplicates that are already in the file. Using listBox.Clear() only clears the control in memory — it does not remove lines already on disk. was correct that reading existing file values into a collection and checking for duplicates is a clean approach; the examples below show two practical, different ways to implement that.

// Overwrite file so it contains only current ListBox items (WinForms)
var lines = listBox1.Items
    .Cast<object>()
    .Select(i => i.ToString().Trim())
    .Where(s => !string.IsNullOrEmpty(s))
    .ToArray();

File.WriteAllLines(path, lines, Encoding.Default);
// Append only new items (skip duplicates, case-insensitive)
var existing = File.Exists(path)
    ? new HashSet<string>(File.ReadAllLines(path, Encoding.Default), StringComparer.OrdinalIgnoreCase)
    : new HashSet<string>(StringComparer.OrdinalIgnoreCase);

var toAppend = listBox1.Items
    .Cast<object>()
    .Select(i => i.ToString().Trim())
    .Where(s => !string.IsNullOrEmpty(s) && !existing.Contains(s))
    .ToArray();

if (toAppend.Length > 0)
    File.AppendAllLines(path, toAppend, Encoding.Default);

Notes and cautions: if this runs in ASP.NET use Server.MapPath or HostingEnvironment.MapPath and write to App_Data, and make sure the app pool identity has write permission. For concurrent writers use a lock or switch to a data store to avoid race conditions.

Recommended Answers

All 3 Replies

Try this code:

private void button1_Click(object sender, EventArgs e)
        {
            string path = @"C:\1\test21.txt";
            if (!File.Exists(path))
            {
                FileStream fs = File.Create(path);
                fs.Close();
            }

            using (TextWriter tw = File.AppendText(path))
            {
                foreach (string item in listBox1.Items)
                    tw.WriteLine(item);
            }
        }

This code addes (appends) the text from listBox to the file (which is being created for the 1st time automatically).

Hope it helps,
Mitja

But now, the previous data also save in that text file.I use the listBox.Clear() to clear the previous data. i just want the latest data.After i saved, the previous data also include inside the text file. How to solve the problem..?

In this case, you have to:
1. get the data out of the file
2. read the data from the file, and check if the value exists do not insert (duplication are missed out), if the value do not exist, insert it into a file.

Or there is another way. Pass the data, which you have already saveed into a file, into some collection object, like an array or generic list, which will suit as the same thing as reading the file and checking which values has been inserted into a file.
When you will want to save the values from listBox for the 2nd time, you wil check is the value is or is not in the list. If is not the value will be instered into the fiel, and vice versa.

PS: And if you want to use this same file many times, the 1st thing when opening the project is to get the values out of the file, and save them into a list. So when the values from listBox will be ready to save into a file, will go again through the checking if every value exists in the list (if not, value can be inserted into a file).

I hope you understand the point here.
Mitja
Only this way you can salve this issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.