Solved

Open and add to textfile using a StreamReader and StreamWriter objects

Posted on 2013-06-18
5
342 Views
Last Modified: 2013-06-18
I have a routine to create a text file.  I use the streamwriter to create the file and write the first line of code.
 Dim fileWriter As New StreamWriter(mFileName2, False)
 fileWriter.Write(mText)
fileWriter.Close()

now the problem is, I close the newly created file and process more, than I need to add another line to the file.   The code I cant figure out will open the newly created file and add a line to the end of the file, then close it and process and repeat.  Not sure how to open new file, read it then add to it.

thanks in advance
0
Comment
Question by:mgmhicks
  • 3
  • 2
5 Comments
 

Author Comment

by:mgmhicks
ID: 39257536
Here is the code I am currently running.

Dim mline As Integer
        Try
            Dim mFileName2 As String = Application.StartupPath & "/" & mFileName
            '  Dim myStream As New FileStream(mFileName2, FileMode.OpenOrCreate, FileAccess.ReadWrite)


            '  Dim fileReader As New StreamReader(mFileName, False)
            If Not File.Exists(mFileName2) Then
                Dim fileWriter1 As New StreamWriter(mFileName2, False)
                fileWriter1.WriteLine(mText)
                fileWriter1.Close()
            Else
                Dim FileReader As New StreamReader(mFileName2, False)
                Dim contents As String = FileReader.ReadToEnd
                FileReader.Close()
                Dim lines() As String = contents.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                Dim mTotalLines As Integer = lines.Count
                'MsgBox(mTotalLines)
                mTotalLines = mTotalLines + 1
                contents.Insert(mTotalLines, mText)

                ' Dim filewriter2 As New StreamWriter(mFileName, False)
                IO.File.AppendText(mFileName).WriteLine(mText)
                ' filewriter2.WriteLine(contents, Environment.NewLine)
                ' filewriter2.Close()
            End If
            WriteAchFile = True
        Catch ex As Exception
            WriteAchFile = False
            MsgBox(ex.Message)
        End Try

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 39257648
See the help for AppendText():
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.IO.FILE.APPENDTEXT);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-VB)&rd=true

    "If the file specified by path does not exist, it is created. If the file does exist, write operations to the StreamWriter append text to the file."

So you can get rid of all that code and simply do:
        Try
            Dim mFileName2 As String = Path.Combine(Application.StartupPath, mFileName)
            IO.File.AppendText(mFileName).WriteLine(mText)
            WriteAchFile = True
        Catch ex As Exception
            WriteAchFile = False
            MsgBox(ex.Message)
        End Try

Open in new window


This will create the file if it doesn't exist, and otherwise will simply append to it.
0
 

Author Comment

by:mgmhicks
ID: 39257950
On 2nd run into code, I get process can not run ("path of file") in use by another process, like the file is still open.

thanks
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 39257974
Try it with a "Using" block which will cause the file to be properly closed:
        Try
            Dim mFileName2 As String = Path.Combine(Application.StartupPath, mFileName)
            Using SW As StreamWriter = IO.File.AppendText(mFileName)
                SW.WriteLine(mText)
            End Using
            WriteAchFile = True
        Catch ex As Exception
            WriteAchFile = False
            MsgBox(ex.Message)
        End Try

Open in new window

0
 

Author Closing Comment

by:mgmhicks
ID: 39257979
Thank you very much.  That works great!!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now