Solved

Open and add to textfile using a StreamReader and StreamWriter objects

Posted on 2013-06-18
5
350 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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

This script will sweep a range of IP addresses (class c only, 255.255.255.0) and report to a log the version of office installed. What it does: 1.)      Creates log file in the directory the script is run from (if it doesn't already exist) 2.)      Sweep…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

821 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