Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Open and add to textfile using a StreamReader and StreamWriter objects

Posted on 2013-06-18
5
Medium Priority
?
354 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

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…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

715 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