Results 1 to 12 of 12

Thread: [RESOLVED] stream reader/writer woes

  1. #1

    Thread Starter
    Lively Member irishlad's Avatar
    Join Date
    Oct 2006
    Location
    Arizona
    Posts
    108

    Resolved [RESOLVED] stream reader/writer woes

    I'm not sure if the coding is correct but I get a file not found error with my dim statement:
    Dim mystreamreader As New StreamReader("C:\test.txt", True) if I change it to ("C:\Some_Directory_Name\test.txt", true) i get an error stating that the file is being used by another process.

    From every example I have read or examined this seems to be the standard in the Form_load event. I'm confused as to where is should go, along with all the other required code. What exactly goes where as in the Dim statement, what if anything goes in the open and save dialog events? Can I put everything into a btnclick event for say reading? this is what I have so far.

    Code:
    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            Dim mystreamreader As New StreamReader("C:\test.txt", True)
            Dim mystreamwriter As New StreamWriter("C:\test.txt", True)
    
            While mystreamreader.Peek <> -1
                Me.lbxInput.Items.Add(mystreamreader.ReadLine)
            End While
            mystreamreader.Close()
            mystreamreader.Dispose()
    
            For Each line As String In Me.lbxInput.Items
                mystreamwriter.WriteLine(line)
            Next
            mystreamwriter.Close()
            mystreamwriter.Dispose()
    Code:
    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
            OpenFileDialog1.InitialDirectory = "C:\test.txt"
            OpenFileDialog1.Title = "Select a File"
            OpenFileDialog1.FileName = ""
            OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt"
            OpenFileDialog1.FilterIndex = 1
        End Sub
    
        Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
            SaveFileDialog1.InitialDirectory = "C:\test.txt"
            SaveFileDialog1.Title = "Specify destination filename"
            SaveFileDialog1.Filter = "Text files (*.txt)|*.txt"
            SaveFileDialog1.FilterIndex = 1
            SaveFileDialog1.OverwritePrompt = True
        End Sub

  2. #2
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,739

    Re: stream reader/writer woes

    Try this in Form Load:
    2 Code:
    1. Using mystreamreader As New StreamReader("C:\test.txt", True)
    2.             While mystreamreader.Peek <> -1
    3.                 Me.lbxInput.Items.Add(mystreamreader.ReadLine)
    4.             End While
    5.             mystreamreader.Close()
    6.         End Using
    7.  
    8.         Using mystreamwriter As New StreamWriter("C:\test.txt", True)
    9.             For Each line As String In Me.lbxInput.Items
    10.                 mystreamwriter.WriteLine(line)
    11.             Next
    12.             mystreamwriter.Close()
    13.  
    14.         End Using
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  3. #3

    Thread Starter
    Lively Member irishlad's Avatar
    Join Date
    Oct 2006
    Location
    Arizona
    Posts
    108

    Re: stream reader/writer woes

    After some tweaking i moved the dim statements and the code for reader/writer respectively to the toolbar save and load. I get no errors and everything runs fine now except for:

    1. the save just adds text to the text file like a log and does not replace it, just adds to it. also the save as window that lists the directory where you want to save and the name of the file you want to change never pops up.

    2. The same for the open, no window to select what file.

    i'm sure the code is pretty easy to check if the file exists, and/or replace it, LOL i say that now before I try, but how do I code to get the open and save dialog box to choose the path and file name? Or will the code you provided do all that?

  4. #4
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,739

    Re: stream reader/writer woes

    Regarding point 1: if you use this declaration it will overwrite any existing text in a file instead of being appended:

    vb Code:
    1. Dim mySW As New IO.StreamWriter("C:\file.txt", False)

    Regarding point 2. You have to show the Window using .ShowDialog:
    2 Code:
    1. With Me.SaveFileDialog1
    2.             .InitialDirectory = "C:\test.txt"
    3.             .Title = "Specify destination filename"
    4.             .Filter = "Text files (*.txt)|*.txt"
    5.             .FilterIndex = 1
    6.             .OverwritePrompt = True
    7.  
    8.             If .ShowDialog = Windows.Forms.DialogResult.OK Then
    9.                 If .FileName <> String.Empty Then
    10.  
    11.                     'Code here
    12.  
    13.                 End If
    14.             End If
    15.         End With
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  5. #5
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: stream reader/writer woes

    No need for
    Code:
    Me.
    And here is what i came up with....
    Code:
    Import System.IO
    
    Public Class FrmMain
    
    Public FileName As String
    
    Private Sub BtnSave_Click()
    
    Dim StreamW as StreamWriter
    With SaveFileDialog1
             .Title = "Save File"
             .FileName = FileName
             .Filter = "Text files (*.txt)|*.txt"
             .FilterIndex = 1
             .OverWritePromt = True
    
            If .ShowDialog = DialogResult.OK Then
               If .FileName <> String.Empty Then
                      FileName = .FileName
                      StreamW = New StreamWriter(FileName)
                      StreamW.Write(TextBox1.Text)
                 End With
    End Sub
    End Class

  6. #6
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,739

    Re: stream reader/writer woes

    You haven't closed the streamWriter when finished. In VB 2005 you should make use of the Using statement to dispose short-lived disposable objects. I've been advised to always use a Using statement where you can:
    vb Code:
    1. Using SW As New IO.StreamWriter(.FileName, False)
    2.  
    3.         'Write contents e.g. SW.WriteLine(line)
    4.  
    5.         SW.Close()
    6. End Using
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  7. #7
    Addicted Member Abrium's Avatar
    Join Date
    Feb 2007
    Location
    The Great State of Texas
    Posts
    205

    Re: stream reader/writer woes

    Stim your going to be a streamreader/writer brain child aren't you, hehe.
    Abrium
    Asking the beginners questions so you don't have to!
    If by chance hell actually froze over and I some how helped you... Please rate.

  8. #8
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,739

    Re: stream reader/writer woes

    There's no need for the StreamWriter really (in this case). Usually only use it to do things with formatting and other extra things. To keep things simple it could be written like this in the appropriate place:

    vb Code:
    1. My.Computer.FileSystem.WriteAllText(.FileName, line, False)
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  9. #9

    Thread Starter
    Lively Member irishlad's Avatar
    Join Date
    Oct 2006
    Location
    Arizona
    Posts
    108

    Re: stream reader/writer woes

    OK, this is what I have, I got everything working now except if I try to change the file name in Savefiledialog1 I keep getting msgbox that states "file does not exist, verify that the correct file name was given" I added a FILE.CreateText line statment but it isn't working, don't know what i'm missing or doing wrong. How can i get it to make a new file name?

    Code:
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    
            Dim mystreamwriter As New StreamWriter("C:\test.txt", True)
            Dim i As Long = lbxInput.Items.Count
            Dim filename As String = "C:\test.txt"
    
            SaveFileDialog1.InitialDirectory = "C:\test.txt"
            SaveFileDialog1.Title = "Specify destination filename"
            SaveFileDialog1.Filter = "Text files (*.txt)|*.txt"
            SaveFileDialog1.FilterIndex = 1
            SaveFileDialog1.OverwritePrompt = True
            SaveFileDialog1.FileName = filename
    
    
            If SaveFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.Cancel Then
               
                For i = 0 To lbxInput.Items.Count - 1
                    mystreamwriter.WriteLine(lbxInput.Items(i))
                Next i
            End If
            If File.Exists(filename) = False Then
                mystreamwriter = New StreamWriter(filename, True)
                mystreamwriter = File.CreateText(filename)
            End If
            mystreamwriter.Close()
            mystreamwriter.Dispose()
    
        End Sub

  10. #10
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,739

    Re: stream reader/writer woes

    It creates one automatically for you if it doesn't already exist. There are a few problems with your code:

    This isn't a directory is it...
    vb Code:
    1. SaveFileDialog1.InitialDirectory = "C:\test.txt"

    A fileName can simply be a name rather than a full path.
    vb Code:
    1. SaveFileDialog1.FileName = filename

    The main problem is your logic. You create a StreamWriter with a path before they have chosen where to Save it. That's what's really causing problems. Declare and use the Streamwriter once the checks for the OK button have been done and the fileName field isn't empty (see below).

    For the streamWriter try implementing Using/End Using as suggested above for the StreamWriter. What's the point of asking for help, getting that help and then promptly ignoring it??

    vb Code:
    1. Using OFD As New SaveFileDialog
    2.  
    3.          OFD.InitialDirectory = "C:\Temp\"
    4.          OFD.FileName = "myFile"
    5.          OFD.DefaultExt = "text"
    6.          OFD.AddExtension = True
    7.          OFD.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
    8.  
    9.          If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
    10.              If OFD.FileName <> String.Empty Then
    11.                  Using sw As New IO.StreamWriter(OFD.FileName, False)
    12.                      For Each str As String In Me.ListBox1.Items
    13.                          sw.WriteLine(str)
    14.                      Next
    15.                      sw.Close()
    16.                  End Using
    17.              End If
    18.          End If
    19. End Using
    Last edited by stimbo; Apr 30th, 2007 at 10:48 AM.
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  11. #11

    Thread Starter
    Lively Member irishlad's Avatar
    Join Date
    Oct 2006
    Location
    Arizona
    Posts
    108

    Re: stream reader/writer woes

    That worked great thanx. Stim I wasn't ignoring your help, it was a few hours from my last post to your last post, in the mean time I was trying to figure it out myself. I had similar code in the form_load procedure that wasn't working so I went back to what I had in the btnsave_click event, which made more sense to me. Then tweeked it and got everything working except for my last issue. I didn't want to get more confused is all. The main thing is you have been great in assisting me and I know I ask a lot of questions asking for a lot of detail so I can learn, I didn't want to just throw your code in my program and getting it running, I'll never learn that way. sometimes I have too because i'm so baffled or didn't know a particular function or method existed, sometimes just to reverse engineer it and pick it apart and make sense of it and change it around and play with it to get a better understanding is all. So I apologize if I offended you in any way.

  12. #12
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,739

    Re: [RESOLVED] stream reader/writer woes

    I'm not offended at all. I know you are only starting VB. Making mistakes is all part of it. I just don't see that big a leap from saying:
    vb Code:
    1. Dim SW As New StreamWriter(etc...)
    2.  
    3. SW.Dispose
    to

    vb Code:
    1. Using SW As New StreamWriter(etc...)
    2.  
    3. End Using

    The rest of the code is exactly the same.
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width