2011-09-18 96 views
1

我在使用C#編寫程序時遇到問題。字符串作爲文件名C#

我想從ListBox1中到文本文件,這是從ListBox2項目命名的保存字符串變量,喜歡這裏:

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

我應該更換xxxxx有就有ListBox2.SelectedItem,例如製作文件「test.txt」。

回答

4

您可以替換xxxxx本:

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); 
    } 
} 

您應該使用usingIDisposable對象。

+0

OP想知道如何從列表框中獲取文件名,而不是硬編碼它。 – Gabe