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

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.