![](/img/trans.png)
[英]Write to textbox.text while running backgroundworker VB.net
[英]StreamWrite unable to write textbox.Text into a .txt file (Vb.net)
我一直在尋找和嘗試多種解決方案來解決這個問題。 我正在嘗試將文本框的結果保存為.txt文件中的一行文本。
以下是我嘗試調用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中的文本永久填充為項目的ComboBox。 我認為使用.txt文件內容填充ComboBox將是最簡單和最實用的方法,但是我認為它比較困難。
你可以試試這個
File.WriteAllText("c:\textfile.txt", TextBox1.Text)
但提到了;
Imports System.IO
如果要寫入文件一次,請執行以下操作:
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
block語句(我省略了它,因為我不確定您是否知道它是什么並且不想引起混淆),這將自動關閉StreamWriter
對象,即使發生錯誤, 像這樣:
' Create a file to write to.
Using sw = File.CreateText(path)
sw.WriteLine(TextBox1.Text)
sw.Flush()
End Using
正如您所看到的,它使代碼更簡單,並消除了清理StreamWriter
對象的擔憂。
事實證明我能夠很容易地解決這個問題。 再次告訴我,我不應該熬夜編碼:/
我所要做的就是添加一行:
totalprofiles.Close()
直接在啟動StreamWriter之后。 否則它似乎根本不想寫任何東西,無論它是由什么產生的。
非常感謝那些幫助過的人,它教會了我“使用”聲明的有用性,我肯定會嘗試將其納入我的程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.