2013-02-15 45 views
1

我試圖檢查文件是否存在,如果是這樣,它什麼也不做。如果文件不存在則創建文本文件。然後我想寫文本到該文件。我在哪裏錯了這個代碼?我只是試圖寫入多行文本文件,該部分不工作。它正在創建文本文件...只是沒有寫入它。使用Visual Basic將多行寫入文本文件

Dim file As System.IO.FileStream 
Try 
    ' Indicate whether the text file exists 
    If My.Computer.FileSystem.FileExists("c:\directory\textfile.txt") Then 
    Return 
    End If 

    ' Try to create the text file with all the info in it 
    file = System.IO.File.Create("c:\directory\textfile.txt") 

    Dim addInfo As New System.IO.StreamWriter("c:\directory\textfile.txt") 

    addInfo.WriteLine("first line of text") 
    addInfo.WriteLine("") ' blank line of text 
    addInfo.WriteLine("3rd line of some text") 
    addInfo.WriteLine("4th line of some text") 
    addInfo.WriteLine("5th line of some text") 
    addInfo.close() 
End Try 
+0

什麼放在第一位讓你覺得有什麼不對的代碼?你有錯誤還是意外的行爲? – 2013-02-15 21:55:34

+0

是的,「textfile.txt」在目錄文件夾中創建,但它不會讓我寫入文件。我得到一個錯誤,說mscorlib.dll 中發生類型'System.IO.IOException'的第一次機會異常進程失敗:System.Windows.Forms.MouseEventArgs – 2013-02-15 21:57:47

+0

這是否編譯?你有一個沒有'Catch'或'Finally'的'Try'。 – 2013-02-15 22:06:27

回答

11

您似乎沒有正確釋放您使用此文件分配的資源。

確保您始終包裹IDisposable資源使用報表,以確保所有資源都正常,只要你已經完成了他們的工作發佈:

' Indicate whether the text file exists 
If System.IO.File.exists("c:\directory\textfile.txt") Then 
    Return 
End If 

Using Dim addInfo = File.CreateText("c:\directory\textfile.txt") 
    addInfo.WriteLine("first line of text") 
    addInfo.WriteLine("") ' blank line of text 
    addInfo.WriteLine("3rd line of some text") 
    addInfo.WriteLine("4th line of some text") 
    addInfo.WriteLine("5th line of some text") 
End Using 

但在你的情況下,使用File.WriteAllLines方法似乎更適當:

' Indicate whether the text file exists 
If System.IO.File.exists("c:\directory\textfile.txt") Then 
    Return 
End If 

Dim data As String() = {"first line of text", "", "3rd line of some text", "4th line of some text", "5th line of some text"} 
File.WriteAllLines("c:\directory\textfile.txt", data) 
+0

你真了不起!有用!!! :D – 2013-02-15 22:14:40

1

這一切都很好! - 這不是創建和寫入文件的最佳方式 - 我寧願創建我想要寫入的文本,然後將其寫入新文件,但給定您的代碼,所缺少的就是不得不關閉在寫入之前創建文件。 只是改變這一行:

file = System.IO.File.Create("c:\directory\textfile.txt") 

到:

file = System.IO.File.Create("c:\directory\textfile.txt") 
file.close 

所有其餘的將正常工作。

+4

@達林的回答是更爲接受的方式...... +1 – 2013-02-15 22:02:32

1
file = System.IO.File.Create("path") 

關閉一旦創建,然後嘗試寫入它的文件。

file.Close() 
    Dim addInfo As New System.IO.StreamWriter("path")