2016-02-29 27 views
1

如何將列表框中的選定項目用作名稱對於新生成的文本文件? (Visual C#中)如何使用列表框中的選定項目作爲名稱對於新生成的文本文件

這裏是一段代碼:

string path = @"C:\\Public Key Pin\Test.txt"; 
if (!File.Exists(path)) 
{ 
    File.Create(path); 
    using (StreamWriter sw = File.CreateText(path)) 
    { 
     sw.WriteLine("The first line!"); 
    } 
} 
else if (File.Exists(path)) 
{ 
    MessageBox.Show("File with this path already exists.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); 
} 
+1

你的問題和代碼沒有多大意義。首先,您正在使用File.Create和File.CreateText兩次重新創建文件。其次,你使用的是什麼UI框架? WinForms,WPF?第三,您想在哪裏使用該值? – Christoph

+0

謝謝,你實際上幫助我處理了另一個問題,因爲我沒有意識到它正在創建兩次文本文件。它給我一個錯誤,說另一個進程正在使用新創建的文件,它給了我一個錯誤,所以謝謝。 –

+0

標題不需要任何標籤 – Muds

回答

1

假設你的列表框ID爲ListBox1

在asp.net 然後嘗試

string path = "C:\\Public Key Pin\"+ListBox1.SelectedItem.Text+".txt 
中的WinForms

試試這個

string path = "C:\\Public Key Pin\"+ListBox1.GetItemText(ListBox1.SelectedItem)+".txt 
+0

作品像一個夢想,謝謝 –

+0

gald它幫助你..做upvote和標記爲答案,如果你可以:) –

0

嘗試這種情況:

ListBox ls = new ListBox(); 
string path = @"C:\\Public Key Pin\" + ls.SelectedItem.ToString() + ".txt"; 

並覆蓋在此被選擇的類的ToString()方法。

相關問題