CanOz Blog

Neil Knobbe's Blog at vbCity

This blog hosted by:
http://blogs.vbcity.com      
  Home :: Syndication  :: Login

JunJuly 2008Aug
SMTWTFS
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

Archives

Image Galleries

vbCity Blogs

In the previous post I talked about Reading Files.  Now I will show you how to Write Files.

 

Writing to Files is as easy as Reading from Files.  As with Reading Files you need to Import the System.IO Namespace.

 

Imports System.IO

 

As with the StreamReader, writing with StreamWriter can be done in more than one way.  How you Write to the File will also depend on if you want to Write to a New File, Overwrite and existing File or Appending and existing File.

 

Let’s take a look at Writing to a New File.

 

Dim sw As New StreamWriter(PathToFileHere)  ' Declare your StreamWriter and File Path

Dim MyString As String  ' Declare the String you will write to the File

 

MyString = “Blah, Blah, Blah”  ' Set the Value of your String

 

sw.Write(MyString)  ' Write the String to the File

 

sw.Close()  ' Close the StreamWriter

 

The above code will create the File, if it does not Exist and write the String to the File.  (*Caution is advised here as the same code will Overwrite the contents of an existing File.)

 

If you want to Append an Existing File there are a couple of ways to go about it.  As always when working with files you need to add the Imports Statement.

 

Imports System.IO

 

Then you need to add the code that will Append the File.

 

Dim sw As StreamWriter = File.AppendText(PathToFileHere)

Dim MyString As String

 

MyString = “Blah, Blah, Blah”

 

sw.Write(Environment.NewLine & MyString)

 

sw.Close()

 

You can also use WriteLine()

 

Imports Sytsem.IO

 

Dim sw As New StreamWriter(PathToFileHere)

Dim MyString As String

 

MyString = “Blah, Blah, Blah”

 

sw.WriteLine(Environment.NewLine & MyString)

 

sw.Close()

 

Hopefully this quick look at Writing to Files gives you a start on Writing Files.

posted on Monday, November 28, 2005 7:48 PM