2013-11-02 103 views
0

我有以下代碼:Streamwriter不向文件添加文本?

If line = Nothing Then 
    MsgBox("Login failed.") 
     Using sw As New StreamWriter(File.Open(Index.strLogPath, FileMode.OpenOrCreate)) ' open or create a new file at our path 
     sw.BaseStream.Seek(0, SeekOrigin.End) ' append new users to the end 
     sw.AutoFlush = True 
     sw.WriteLine("line is nothing") 
     sw.Flush() 
     sw.Close() 
     End Using 

End If 

我行=什麼條件滿足時,MSGBOX彈出讓我知道,但不創建的文件。如果該文件在那裏,則不會添加任何內容。

我檢查了路徑有效性,並確保應用程序在那裏有權限,我能想到的所有內容都無法正常工作,並且使其更加令人沮喪並且沒有錯誤!任何幫助將不勝感激。

+0

有沒有原因您沒有使用[File.AppendAllText方法](http://msdn.microsoft.com/en-us/library/ms143356%28v=vs.110%29.aspx) ?那麼'線路'的類型是什麼?你應該使用'Is'而不是'='來比較VB.NET中的'Nothing'。你是否在用空白字符串混淆空字符串?有[String.IsNullOrEmpty](http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx)可用。 –

+0

如果你在同樣的代碼中使用'MsgBox(Index.strLogPath)',它是否顯示所需的文件名? –

+0

@AndrewMorton是的,它顯示了txt文件的確切路徑。 – SCGB

回答

1

你知道嗎File類已經有一個實用的方法來做到這一點?

File.AppendAllText(Index.strLogPath, "line is nothing") 

應該那麼簡單。 :)

編輯

如果你堅持管理文件流,試試這個:

Using sw As New StreamWriter(File.Open(Index.strLogPath, FileMode.Append)) ' open or create a new file at our path 
     sw.WriteLine("line is nothing") 
    End Using 

問題的興趣:

  • 使用FileMode.Append而不是OpenOrCreate
  • 無需沖洗或關閉。這是在您離開「使用」塊時自動完成的。
相關問題