1

I have a problem writing a program in C#.

I want to to save string variables from a ListBox1 to textfile, which is named after the item from ListBox2, like here:

Write = new StreamWriter(xxxxx);
for (int I = 0; I < ListBox1.Items.Count; I++)
{
    Text = (SubCategories.Items[I]).ToString();
        Write.WriteLine(Text);
}
Write.Close();

What should I replace xxxxx to have there ListBox2.SelectedItem, for example to make file "test.txt".

1 Answer 1

4

You can replace xxxxx with this:

var path = Path.Combine(Environment.CurrentDirectory, ListBox2.SelectedItem.ToString());

using (var writer = new StreamWriter(path))
{
    for (int I = 0; I < ListBox1.Items.Count; I++)
    {
        Text = (SubCategories.Items[I]).ToString();
        writer.WriteLine(Text);
    }
}

You should use a using with IDisposable objects.

Sign up to request clarification or add additional context in comments.

1 Comment

OP Wanted to know how to get the filename from a listbox, not hardcode it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.