To create a text file in VB.net code should be one of the tools in every developers toolbox and the normal approach is to use a StreamWriter to accomplish this which gives us some greater control over the creation of the file, but if we just want to write out a quick file to disk such as a text or csv file then we can do this in a single line of code using
For Example, in the below code we create a string builder add some lines and then we write the string builder out to a text file on disk called "C:test.txt"
Dim sTextFile As New System.Text.StringBuilder sTextFile.AppendLine("The") sTextFile.AppendLine("brown") sTextFile.AppendLine("fox") sTextFile.AppendLine("jumps") Dim sFileName As String = "C:\test.txt" System.IO.File.AppendAllText(sFileName, sTextFile.ToString)
If our "test.txt" file doesn't exist then
System.IO.File.AppendAllText will create the file for us and after writing the text data will then close the file without us needing to do any additional work, if "test.txt" does exist then the file will be opened and the text appended to the file before the file being closed again and we get all this functionality from a single line of code which is pretty cool.
For more information on
System.IO.File.AppendAllText check out the MSDN page http://msdn.microsoft.com/en-us/library/system.io.file.appendalltext(v=vs.110).aspx