2013-08-16 27 views
0

我一直在尋找並嘗試多種解決方案來解決我遇到的這個問題。我試圖將文本框的結果保存爲.txt文件中的一行文本。StreamWrite無法將textbox.Text寫入.txt文件(Vb.net)

以下是我嘗試調用StreamWriter執行此操作之前,之時和之後的代碼。

If inttAnswer = vbOK Then 
       totalprofiles.Write(filename & vbNewLine) '*this is not working* 
       txtProfileName.Text = "" 
       Me.Hide() 
       Profiles.StartPosition = FormStartPosition.Manual 
       Profiles.Location = Me.Location 
       Profiles.Show() 
    End If 

下面是我使用的這部分代碼,它是當按下按鈕時的代碼塊的一部分的任何聲明:

Dim totalprofiles2 As String = "C:\SameSens\Profiles\TotalProfiles.txt" 
    Dim totalprofiles As New System.IO.StreamWriter(totalprofiles2, True) 

    Dim inttAnswer As Integer 
    Dim filename As String = txtProfileName.Text 

感謝您的幫助。 如果這是不可能的,也許你可以建議一個不同的/更好的替代方案,一旦這個特定的按鈕被按下,就可以將txtProfileName.Text中的文本作爲一個項目填充到組合框中。我認爲用.txt文件內容填充ComboBox將是最簡單和最實用的方式,但是我認爲它證明更困難。

回答

1

你可以試試這個

File.WriteAllText("c:\textfile.txt", TextBox1.Text) 

但把一個參考;

Imports System.IO 
1

如果你想寫入文件一次,然後做到這一點:如果你想保留追加到一個文件,並把它隨時間增長

Dim path As String = "PathToYourFile.txt" 
Dim sw As StreamWriter 

If File.Exists(path) = False Then 
    ' Create a file to write to. 
    sw = File.CreateText(path) 

    sw.WriteLine(TextBox1.Text) 

    sw.Flush() 
    sw.Close() 
End If 

,那麼這樣做:

Dim path As String = "PathToYourFile.txt" 
Dim sw As StreamWriter 

If File.Exists(path) Then 
    ' Append text to file, adding new text to the end of the file 
    sw = File.AppendText(path) 

    sw.WriteLine(TextBox1.Text) 

    sw.Flush() 
    sw.Close() 
End If 

注意:建議您使用Using塊語句(我省略了它,因爲我不確定是否知道它是什麼並且不想造成混淆),它會自動關閉在StreamWriter對象,即使出現錯誤,就像這樣:

' Create a file to write to. 
Using sw = File.CreateText(path) 
    sw.WriteLine(TextBox1.Text) 

    sw.Flush() 
End Using 

正如你可以看到它使代碼更簡單,並消除了清理StreamWriter對象的擔心。

+0

請不要寫'= True'。 – Ryan

+0

@minitech - 我已經刪除了'= True',它是故意完成的,因爲我想清楚地顯示反對的邏輯,但我理解你的觀點。 –

+0

非常感謝關於「使用」的提示。 – user2689736

0

原來我很容易解決這個問題。告訴我,我又不能熬夜編碼:/

我所要做的就是添加一行:

totalprofiles.Close() 

發起的StreamWriter後直接。否則,它似乎不想寫任何東西,不管它是從哪裏來的。

非常感謝兩位幫助過的人,它教會了我關於「使用」聲明的用處,我一定會嘗試將它融入到我的程序中。