开发者

String as a file name C#

开发者 https://www.devze.com 2023-04-06 05:24 出处:网络
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:

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 f开发者_开发知识库ile "test.txt".


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消