2014-01-23 18 views
-2

我使用Visual Studio 2013和C#從一個文本框以用戶輸入來創建一個文本文件名

我現在有一個形式,在其他項目中,有用戶輸入ID號碼的文本。我希望能夠'取得'這個號碼並創建一個ID號爲文件名的文本文件。

我已經能夠使用OpenFileDialog和Streamwriter寫入文件,但這需要用戶單擊「保存位置」按鈕並瀏覽到文件位置,然後輸入他們想要創建的文件的文本。

我寧願讓程序根據ID號創建.txt文件,以便他們可以輸入他們的ID,然後按回車鍵啓動程序。

這可能嗎?

+2

這樣的事情? http://stackoverflow.com/questions/9907682/create-a-txt-file-if-its-not-exist-and-if-it-exist-write-a-line-with-c-sharp – Goose

+0

什麼@鵝說。如果您希望他們選擇一個文件夾(但仍自動創建文件名),請查看[FolderBrowserDialog](http://msdn.microsoft.com/zh-cn/library/system.windows.forms.folderbrowserdialog %28V = vs.110%29.aspx)。 – admdrew

+0

謝謝@Goose在發佈我的問題之前,我想我已經搜索了其他答案。答案的一部分肯定有助於我的查詢。 – smokeAndMirrors

回答

1

是的,這是可能的,這是微不足道的。如果您想使用您的StreamWriter,只需將我的File.WriteAllText替換爲您的StreamWriter代碼即可。

button_click_handler(fake args) 
{ 
    string fileName = MyTextBox.Text; 
    File.WriteAllText(basePath + fileName, "file contents"); 
} 
+0

所以這將創建文件,如果它不存在,並添加到它,如果它不? – smokeAndMirrors

+0

@smokeAndMirrors它覆蓋文件,如果它在那裏。它只是寫無論如何。 – evanmcdonnal

1

當然這是可能的。在你的問題中唯一不清楚的地方就是你想創建這個文本文件的位置以及你想要在其中存儲什麼。

string fileName = txtForFileName.Text; 
// create a path to the MyDocuments folder 
string docPath = Environment.GetFolderPath(Environment.SpecialFolders.MyDocuments); 
// Combine the file name with the path 
string fullPath = Path.Combine(docPath, fileName); 

// Note that if the file exists it is overwritten 
// If you want to APPEND then use: new StreamWriter(fullPath, true) 
using(StreamWriter sw = new StreamWriter(fullPath)) 
{ 
    sw.WriteLine("Hello world"); 
} 

我認爲你可以找到非常有用的看着這個MSDN網頁約Common I/O Tasks

0

有很多方法可以做到這一點。

string thepath = String.Format("{0}{1}{2}","C:\\PutDestinationHere\\",idTextBox.text,".txt"); 

using(StreamWriter writer = new StreamWriter(thepath)) 
    { 
    writer.WriteLine(); 
    } 
相關問題