File.WriteAllText(sfd.FileName, string.Join("|", myForm.listBox.Items.OfType<string>()));
Update: The above solution is based on the information provided. You imply that the data in the list are simple strings, So the above code joins strings and writes them to disk as a continuous string.
If you are using complex objects like classes, then you need to do more work to serialize the object before you can write it to disk.
Here is a [Newtonsoft] JSON helper for serializing and deserializing:
using Newtonsoft.Json;
using System.Collections.Generic;
namespace DotNet.Shared.Helpers
{
public static class JsonConverter
{
public static string FromClass<T>(T data, bool isEmptyToNull = false, JsonSerializerSettings jsonSettings = null)
{
string response = string.Empty;
if (!EqualityComparer<T>.Default.Equals(data, default(T)))
response = JsonConvert.SerializeObject(data, jsonSettings);
return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
}
public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
{
var response = default(T);
if (!string.IsNullOrEmpty(data))
response = jsonSettings == null
? JsonConvert.DeserializeObject<T>(data)
: JsonConvert.DeserializeObject<T>(data, jsonSettings);
return response;
}
}
}
And to use:
File.WriteAllText(sfd.FileName, JsonConverter.FromClass(listBox1.Items.OfType<Person>()));
UPDATE #2: You will always have blank files because of this line:
var myForm = new FormVer();
Instead of creating a new form with empty data, you need to point to the active form with the data. Something like:
var myForm = Application.OpenForms[nameof(FormVer)];