我在除錯檔案夾中有一個文本檔案,我需要能夠用新的、隨機的、已編輯的文本覆寫它。問題是它不斷出現: System.IO.IOException: 'Bad file mode.' 我該如何解決?
這是代碼:
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
If txtToFile.Text = "" Then
If MsgBox("YOU ARE ABOUT TO SAVE THIS DOCUMENT AS A BLANK!!! Are you sure you want to override this file?", vbYesNo vbQuestion vbCritical, "WARNING!") = vbYes Then 'If the override button is clicked and the user has confirmed that they want to clear the file
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, "enrolments.txt", OpenMode.Input) 'open file
PrintLine(FileNum, txtToFile.Text) 'write text to file
FileClose(FileNum) 'close the file
End If
Else
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, "enrolments.txt", OpenMode.Input) 'open file
PrintLine(FileNum, txtToFile.Text) 'write text to file
FileClose(FileNum) 'close the file
MessageBox.Show("File Written Over Successfully!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
我對這個編碼仍然很陌生,所以如果你能通過你的解決方案解釋你的推理,那將不勝感激!謝謝!:D
uj5u.com熱心網友回復:
例外的原因OpenMode.Input是應該在讀取檔案時使用,而不是寫入檔案。由于您正在嘗試覆寫檔案,因此您應該OpenMode.Output改用。
您也不需要重復相同的代碼兩次。您可以檢查 TextBox 是否為空,顯示警告訊息,然后無論如何都寫入檔案。您的代碼應如下所示:
Dim textBoxIsEmpty As Boolean = (txtToFile.Text.Length = 0)
If textBoxIsEmpty Then
If MsgBox("...", vbYesNo vbQuestion vbCritical, "WARNING!") <> vbYes Then Exit Sub
' Or...
'If MessageBox.Show("...", "WARNING!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) <> DialogResult.Yes Then Exit Sub
End If
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, "enrolments.txt", OpenMode.Output) 'open file for writing
PrintLine(FileNum, txtToFile.Text) 'write text to file
FileClose(FileNum) 'close the file
If Not textBoxIsEmpty Then
MessageBox.Show("File Written Over Successfully!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
話雖如此,正如Andrew Mortimer在評論中所建議的那樣,您應該熟悉讀取和寫入檔案的標準 .NET 方式(即,使用System.IO命名空間中的類和方法。本指南是一個好的開始. 你會發現覆寫一個文本檔案就像這行代碼一樣簡單:
IO.File.WriteAllText("enrolments.txt", txtToFile.Text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473631.html
