Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Open and add to textfile using a StreamReader and StreamWriter objects

Posted on 2013-06-18
5
Medium Priority
?
355 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 86

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 86

Accepted Solution

by:
Mike Tomlinson earned 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

927 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