OpenFileDialog help needed

I'm using the code below to open a file from the target directory and display it to a multi line textbox, I need help in getting stream reader to open the file so it can be appended... curser at the end of the last entry in the file ready for a new entry to be added instead of it being in the first postion on first line.  Once the file has a new entry added to it then I need extra code to save the file like the File/Save in Notepad, I also need more code for a  File Save As method to save a backup copy of the file to a startup path directory Application.StartupPath() & "\Backup Number Files\"

What's below is all I have so far... working code for the rest of my description above would be greatly appreciated.  I'm using .NET 2005 and it's basic File/open   File/save   File/save as but i'm kinda new to .NET so I have a learning deficiency so far.

I'd also like to know if there's a way to get the title of the form to change to the name of the file I open.... also like Microsoft's Notepad does. Points go to the most help on all the above problems/questions.


Imports System.IO

Public Class Analyzer

    Dim FileName As String = Application.StartupPath() & "\Number Files\"
    Dim sr As StreamReader


    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click

        Dim supportPath As String = Application.StartupPath() & "\Number Files\"
        OpenFileDialog1.Title = "Please select a game file to open"
        OpenFileDialog1.InitialDirectory = supportPath
        OpenFileDialog1.FileName = ""
        Try
            With OpenFileDialog1
                .Filter = "Game Files (*.Game)|*.Game|" & "None|"
                If .ShowDialog() = Windows.Forms.DialogResult.OK Then
                    FileName = .FileName
                    sr = New StreamReader(.OpenFile)
                    TextBox1.Text = sr.ReadToEnd()
                End If
            End With
        Catch es As Exception
            MessageBox.Show(es.Message)
        Finally
            If Not (sr Is Nothing) Then
                sr.Close()
            End If
        End Try
    End Sub
End Class
teamdadAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gladiatorno9Commented:
Hi

Good morning!!

try tis out!

Putting Dialog Boxes to Work

We will work with OpenFile, SaveFile, Font and Color Dialog's in this section. From the toolbox drag a MainMenu component, RichTextBox control, Button Control, OpenFileDialog, SaveFileDialog, FontDialog and ColorDialog onto the form. The sample code demonstrated below allows you to select a file to be opened and displays it in the RichTextBox with OpenFileDialog, allows you to save the text you enter in the RichTextBox to a location using the SaveFileDialog, allows you to select a font and applies the selected font to text in the RTB using FontDialog and allows you to select a color and applies the color to text in the RTB using the ColorDialog. Select the MainMenu component and in the "Type Here" part of the MainMenu type File and using the down arrow keys on the keyboard start typing Open, Save, SelectFont and SelectColor under the File menu. It should look like this: File-> Open, Save, SelectFont, SelectColor. We will assign OpenFileDialog to Open, SaveFileDialog to Save, FontDialog to SelectFont and ColorDialog to SelectColor under File Menu. The form in design view should look similar to the image below.

 

Before proceeding further you need to set properties for these dialogs in their properties window. They are listed below.

For OpenFileDialog1, set the DefaultExt property to txt so that it opens text files, InitialDirectory property to C:, RestoreDirectory propery to True and the Text property to Open File From.

For SaveFileDialog1, set the DefaultExt property to txt so that it saves files in text format, InitialDirectory property to C: so that when you save a file, it first provides C: drive as the choice of location, OverwritePrompt property to False, RestoreDirectory propery to True and the Text property to Save File In.

For FontDialog1, set the AllowSimulations, AllowVectorFonts, AllowverticalFonts properties to false, MaxSize to 50, MinSize to 5 and ShowApply and ShowColor properties to True.

For ColorDialog1, set AnyColor and SolidColorOnly properties to True.

Code

Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

#End Region

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
RichTextBox1.Text = " "
'clears the text in richtextbox
End Sub

Private FileName As String
'declaring filename that will be selected
Dim sr As StreamReader
'streamreader is used to read text

Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MenuItem2.Click
Try
With OpenFileDialog1
'With statement is used to execute statements using a particular object, here,_
'OpenFileDialog1
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
'setting filters so that Text files and All Files choice appears in the Files of Type box
'in the dialog
If .ShowDialog() = DialogResult.OK Then
'showDialog method makes the dialog box visible at run time
FileName = .FileName
sr = New StreamReader(.OpenFile)
'using streamreader to read the opened text file
RichTextBox1.Text = sr.ReadToEnd()
'displaying text from streamreader in richtextbox
End If
End With
Catch es As Exception
MessageBox.Show(es.Message)
Finally
If Not (sr Is Nothing) Then
sr.Close()
End If
End Try
End Sub

Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MenuItem3.Click
Dim sw As StreamWriter
'streamwriter is used to write text
Try
With SaveFileDialog1
.FileName = FileName
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
FileName = .FileName
sw = New StreamWriter(FileName)
'using streamwriter to write text from richtextbox and saving it
sw.Write(RichTextBox1.Text)
End If
End With
Catch es As Exception
MessageBox.Show(es.Message)
Finally
If Not (sw Is Nothing) Then
sw.Close()
End If
End Try
End Sub

Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MenuItem4.Click
Try
With FontDialog1
.Font = RichTextBox1.Font
'initializing the dialog box to match the font used in the richtextbox
.Color = RichTextBox1.ForeColor
'default color is Black
If .ShowDialog = DialogResult.OK Then
setFont()
'calling a method setFont() to set the selected font and color
End If
End With
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

Private Sub setFont()
Try
With FontDialog1
RichTextBox1.Font = .Font
If .ShowColor Then
RichTextBox1.ForeColor = .Color
'setting the color
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub MenuItem5_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MenuItem5.Click
Static CustomColors() As Integer = {RGB(255, 0, 0), RGB(0, 255, 0), RGB(0, 0, 255)}
'initializing CustomColors with an array of integers and putting Red, Green,
'and Blue in the custom colors section
Try
With ColorDialog1
.Color = RichTextBox1.ForeColor
'initializing the selected color to match the color currently used
'by the richtextbox's foreground color
.CustomColors = CustomColors
'filling custom colors on the dialog box with the array declared above
If .ShowDialog() = DialogResult.OK Then
RichTextBox1.ForeColor = .Color
CustomColors = .CustomColors
'Storing the custom colors to use again
End If
ColorDialog1.Reset()
'resetting all colors in the dialog box
End With
Catch es As Exception
MessageBox.Show(es.Message)
End Try
End Sub

End Class  

gladiatorno9Commented:
try out the accepted answer !!!

Create a user interface as shown in the image below. Add the following controls:
txt_watchpath              -        TextBox  (for folder path)
btn_startwatch            -        Button   (start watching)
btn_stop                  -        Button   (stop watching)
txt_folderactivity        -        Textbox  (folder activity)

Lets start coding for this application, first thing we need to do is to import the required classes, type the following code before your class declaration


Imports System.IO
Imports System.Diagnostics

This shall import the necessary class required for our application we also need to declare a public variable for our FileSystemWatcher class


Public watchfolder As FileSystemWatcher

Also add the following code to the btn_start_click procedure.


watchfolder = New System.IO.FileSystemWatcher()

'this is the path we want to monitor
 watchfolder.Path = txt_watchpath.Text

'Add a list of Filter we want to specify
'make sure you use OR for each Filter as we need to
'all of those

watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                           IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                           IO.NotifyFilters.Attributes

' add the handler to each event
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange

' add the rename handler as the signature is different
AddHandler watchfolder.Renamed, AddressOf logrename

'Set this property to true to start watching
watchfolder.EnableRaisingEvents = True

btn_startwatch.Enabled = False
btn_stop.Enabled = True

'End of code for btn_start_click

NotifyFilter propery is used to specify the type of changes you want to watch. You can combine the notify filters to watch for one or more than one type of changes, eg. set the NotifyFilter property to Size if you want to monitor the changes in the file/folder size. Below are the list of notify filters


Attributes              (The attributes of the file or folder)
CreationTime             (The time the file or folder was created)
DirectoryName            (The name of the directory)
FileName            (The name of the file)
LastAccess            (The date the file or folder was last opened)
LastWrite            (The date the file or folder last had anything written to it)
Security            (The security settings of the file or folder)
Size                  (The size of the file or folder)

The default is the bitwise OR combination of LastWrite, FileName, and DirectoryName.
FileSystemWatcher class raises five events, which are Created, Changed, Deleted, Renamed and Error, but because Created, Changed, and Deleted events share the same event signature we can write just one event handler and we shall write one event handler for Renamed, because their event signatures are different.

Lets type code for handling Created, Changed, and Deleted event raised by the FileSystemWatcher class. (Please note you will have to type the event declaration, as this procedure is not generated automatically)


Private Sub logchange(ByVal source As Object, ByVal e As _
                        System.IO.FileSystemEventArgs)
 If e.ChangeType = IO.WatcherChangeTypes.Changed Then
     txt_folderactivity.Text &= "File " & e.FullPath & _
                             " has been modified" & vbCrLf
 End If
 If e.ChangeType = IO.WatcherChangeTypes.Created Then
     txt_folderactivity.Text &= "File " & e.FullPath & _
                              " has been created" & vbCrLf
 End If
 If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
     txt_folderactivity.Text &= "File " & e.FullPath & _
                             " has been deleted" & vbCrLf
 End If
End Sub

This is the code for handling the Renamed event raised by the FileSystemWatcher class.

Public Sub logrename(ByVal source As Object, ByVal e As _
                            System.IO.RenamedEventArgs)
   txt_folderactivity.Text &= "File" & e.OldName & _
                 " has been renamed to " & e.Name & vbCrLf
End Sub

And lastly this is the code for the btn_stop_click, which shall stop the monitor.

' Stop watching the folder
watchfolder.EnableRaisingEvents = False
btn_startwatch.Enabled = True
btn_stop.Enabled = False

 
Finally

Now it's the time to run the application and see it in action, please build and run the application, type the folder you want to monitor in the text box and click start watching to start watching that folder.
In the folder you specified, create a file, rename it, update it and delete it to see our application recording those changes.

More Information

Use FileSystemWatcher.Filter Property to determine what files should be monitored, eg setting filter property to "*.txt" shall monitor all the files with extension txt, the default is *.* which means all the files with extension, if you want to monitor all the files with and without extension please set the Filter property to "".
FileSystemWatcher can be used watch files on a local computer, a network drive, or a remote computer but it does not raise events for CD. It only works on Windows 2000 and Windows NT 4.0, common file system operations might raise more than one event. For example, when a file is edited or moved, more than one event might be raised. Likewise, some anti virus or other monitoring applications can cause additional events.

The FileSystemWatcher will not watch the specified folder until the path property has been set and EnableRaisingEvents is set to true.
Set FileSystemWatcher.IncludeSubdirectories Property to true if you want to monitor subdirectories; otherwise, false. The default is false.
FileSystemWatcher.Path property supports Universal Naming Convention (UNC) paths. If the folder, which the path points is, renamed the FileSystemWatcher reattached itself to the new renamed folder.

Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
gladiatorno9...it's more appropriate to supply links to full articles instead of copying and pasting them as "your own work":
http://www.startvbdotnet.com/controls/dialog1.aspx
http://www.codeproject.com/dotnet/folderwatcher.asp
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

teamdadAuthor Commented:
All nice information from you both but I need help in getting stream reader to open the file so it can be APPENDED... curser at the next blank line in the file ready for a new entry to be added instead of it being in the first postion on first line when the file is opened.  

Once the file has a new entry added to it then I need the code to save the file like the File/Save in Notepad. Where it WON'T tell you the file already exists and if you are sure you want to over write the file.

The code in my first post is all I have so far... working code for the rest of my description above would be greatly appreciated.  I'm using .NET 2005 and I have a learning deficiency so far with .NET

** I'd also like to know if there's a way to get the title of the form to change to the name of the file I open.... also like Microsoft's Notepad does instead of it saying Untitled -Notepad all the time.

 Points go to the best help on all the above problems/questions.
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
teamdad,

Does your app allow the contents of the file to be changed?  It seems like you read the file into a textbox here:
 
    TextBox1.Text = sr.ReadToEnd()

Then is the user allowed to make changes anywhere?

If yes, then you don't need to append, you need to overwrite the whole file with the contents of your textbox.
teamdadAuthor Commented:
Yes, the app is a whole lot like Microsoft's Notepad program.  When the user opens a file it will have a colum of numbers, I need the curser to be at the next blank line when they open the file so they can just typ in the next set of numbers then they can save the file with all the old numbers that was already there plus the new ones they just added.

I'd also like to know if there's a way to get the title of the form to change to the name of the file I open.... also like Microsoft's Notepad does instead of it saying Untitled -Notepad all the time.
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
So really you just need the cursor at the end of the textbox.  You don't need to do anything with the file itself while the user is editing the text.  Here is how to move the cursor and change the title of your form:

                ...
                If .ShowDialog() = Windows.Forms.DialogResult.OK Then
                    FileName = .FileName
                    sr = New StreamReader(.OpenFile)
                    TextBox1.Text = sr.ReadToEnd()

                    TextBox1.SelectionStart = TextBox1.TextLength ' <--- Put cursor at the end of the textbox
                    Me.Text = .FileName ' <--- Change the title of the form to the name of the file

                End If
                ...
teamdadAuthor Commented:
Getting closer....

the cursor is at the end of the last typed set of numbers but I need it to be at the front of the next blank line. If it helps any, the numbers in the file don't go all the way across each line in the file.  There's at most only 8 numbers in total for each line.

TextBox1.SelectionStart = TextBox1.TextLength ' <---add some code to make it simulate pressing the enter key so the cursor jumps to the next line down


The Me.Text = .FileName part puts the whole path in the form's caption text.  I only need it to show the file name without the directory path or file extension.  

The save function hasn't been addressed; it still asks if you want to over write the file that already exists, the Save option in Notepad doesn't do this unless you select Save As.
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
Try this...
               
                    TextBox1.AppendText(VbCrLf)
                    TextBox1.SelectionStart = TextBox1.TextLength ' <--- Put cursor at the end of the textbox
                    Dim fi As New System.IO.FileInfo(.FileName)
                    Me.Text = fi.Name ' <--- Change the title of the form to the name of the file



"The save function hasn't been addressed; it still asks if you want to over write the file that already exists, the Save option in Notepad doesn't do this unless you select Save As."

You don't need a SaveDialog to implement a Save function!  Just store the name of the file in a variable when you open the file.  Then when the user selects File --> Save, just overwrite the file using the stored name and the current contents of the textbox.  You don't need a SaveDialog to do this...
teamdadAuthor Commented:
Well, the  TextBox1.AppendText(VbCrLf) puts a carriage return if there is a line of numbers or not.  If it's a blank file with no entries in it then when it's opened it puts a blank line and cursor starts at the next line.  If there's no line of numbers it should start at the first line for the user to enter their data there instead of having to backspace.

 Dim fi As New System.IO.FileInfo(.FileName)
                    Me.Text = fi.Name ' <--- Change the title of the form to the name of the file

puts the whole path of the file in the title, I only need the file name and not the path or the extension.
teamdadAuthor Commented:
This still isn't resolved.... anyone else want to give it a shot?
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics TeacherCommented:
This works for me...

        Try
            With OpenFileDialog1
                .Filter = "Game Files (*.Game)|*.Game|" & "None|"
                If .ShowDialog() = Windows.Forms.DialogResult.OK Then
                    FileName = .FileName
                    sr = New StreamReader(.OpenFile)
                    TextBox1.Text = sr.ReadToEnd()
                    If TextBox1.TextLength > 0 Then
                        TextBox1.AppendText(vbCrLf)
                    End If
                    TextBox1.SelectionStart = TextBox1.TextLength
                    Debug.WriteLine(FileName)
                    Dim fi As New FileInfo(FileName)
                    Me.Text = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension))
                    TextBox1.Focus()
                End If
            End With
        Catch es As Exception
            MessageBox.Show(es.Message)
        Finally
            If Not (sr Is Nothing) Then
                sr.Close()
            End If
        End Try

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.