2013-02-15 108 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")