File dialog boxes Function args and overloading Examples in this show • • • • • • • List directory contents Open a file for viewing Read/Write to a file Add file I/O to an old project reading/writing array contents Streamreader Overloaded functions Listing text files in a directory File load Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load txtfile.Text = CurDir() End Sub the open button –check for legal path Dim NewPath As String ' NewPath holds the path the user has entered. NewPath = txtfile.Text ' Change the location to NewPath. Dim errormessage As String Try ChDir(NewPath) ' This checks to make sure the path is not blank. Catch ex As Exception When NewPath = "" ErrorMessage = "You must enter a path." ' This catches errors caused by a path that is not valid. Catch ErrorMessage = "You must enter a valid path. If trying" & _ "to access a different drive, remember to include the drive" & _ "letter." Finally ' Display the error message only if one exists. If ErrorMessage <> "" Then MsgBox(ErrorMessage) End If End Try Display txt contents of directory Dim contentitem As String lstData.Items.Clear() ' Only look at the .txt files. ContentItem = Dir("*.txt") If ContentItem = "" Then errormessage = "No text files found." MsgBox(errormessage) End If ' Iterate through the directory contents. Do Until ContentItem = "" ' Add it to the list. lstData.Items.Add(contentitem) ' Move to the next textfile. ContentItem = Dir() Loop Using filedialogs: this is a dialog box “Open” and “save” file dialog boxes are in your toolbox and are added to the component tray Button action • Open and save buttons display the file dialog, get the results of the dialog. • If the result is cancel the sub is exited via a return • If the filename doesn’t end in “.txt” (not a guarantee of anything) the sub is exited. We do this by using the endswith() string function to check the end of the string. • I added a try… catch in the hopes of eliminating file io exceptions which might shut down the application. Button action: open • The open button gets a filename, opens a filereader for a file with this name. • As long as there is more text in the file we read it and append it to our multiline textbox. Button action: Save • The save button gets a filename from the dialog (or a cancel), opens a filewriter for a file with this name. • As long as there is more text (ie. Line by line) in the multi-line textbox we read it and append it to our multi-line textbox. (Multi-line textbox is just a textbox with multi-line property set to true). • We do this by using indexof string function to find a crlf in the contents string and the substring function to cut this part off. Open button Private Sub btnopen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnopen.Click Dim objinput As StreamReader Dim tmp, filename As String Dim result As DialogResult = windows.forms.objOpenFileDialog.ShowDialog If result = DialogResult.Cancel Then Return End If filename = objOpenFileDialog.FileName If filename.EndsWith(".txt") = False Then Return End If Try objinput = New StreamReader(filename) Dim contents As String contents = objinput.ReadLine Do While contents <> "" txtContents.AppendText(contents & ControlChars.CrLf) contents = objinput.ReadLine Loop objinput.Close() Catch ex As Exception End Try End Sub Save button Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click Dim objoutput As StreamWriter Dim tmp As String Dim result As DialogResult = windows.forms.objSaveFileDialog.ShowDialog If result = DialogResult.Cancel Then Return End If Dim filename As String = objSaveFileDialog.FileName If filename.EndsWith(".txt") = False Then Return End If Try objoutput = New StreamWriter(filename) Dim contents As String = txtContents.Text objoutput.WriteLine(contents) objoutput.Close() Catch ex As Exception End Try End Sub Open button Adding file output to a previous project Recommended way to do file i/o • Use a streamwriter and streamreader objects (for writing or reading respectively). • Use a filedialog box for opening or saving a file. • This example should not be used as a basis for file io The save button Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click ' FileOpen will create the file if it doesn't exist. ' value 1 is the file handle Dim errormessage, displaystring As String Dim i, j As Integer Try FileOpen(1, "records.txt", OpenMode.Append)’ this should be redone with stream writer For i = 0 To classsize - 1 displaystring = students(i) For j = 0 To 2 If exams(i, j) = -99 Then displaystring = displaystring & ControlChars.Tab & "no grade" Else displaystring = displaystring & ControlChars.Tab & exams(i, j) End If Next WriteLine(1, displaystring) Next Catch ex As Exception errormessage = ex.ToString() MsgBox(ErrorMessage) Exit Sub Finally FileClose(1) End Try End Sub Open/View and Save Open button provides dialog box Open button code Private Sub btnopen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnopen.Click Dim objinput As StreamReader Dim tmp, filename As String Dim result As DialogResult = objOpenFileDialog.ShowDialog If result = DialogResult.Cancel Then Return End If filename = objOpenFileDialog.FileName If filename.EndsWith(".txt") = False Then Return End If Try objinput = New StreamReader(filename) Dim contents As String contents = objinput.ReadLine Do While contents <> "" txtContents.AppendText(contents & ControlChars.CrLf) contents = objinput.ReadLine Loop objinput.Close() Catch ex As Exception End Try End Sub Create a new file (type contents) Dialog box for save button Save button code Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click Dim objoutput As StreamWriter Dim tmp As String Dim result As DialogResult = windows.forms.objSaveFileDialog.ShowDialog If result = DialogResult.Cancel Then Return End If Dim filename As String = objSaveFileDialog.FileName If filename.EndsWith(".txt") = False Then Return End If Try objoutput = New StreamWriter(filename) Dim contents As String = txtContents.Text objoutput.WriteLine(contents) objoutput.Close() Catch ex As Exception End Try End Sub Filling/saving array contents Saved file contents Save button: open file and write to it Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click ' FileOpen will create the file if it doesn't exist. ' value 1 is the file handle Dim errormessage As String Dim i As Integer Dim outpt As StreamWriter Try outpt = File.CreateText("values2.txt") 'could use dialog box For i = 0 To array.Length - 1 outpt.WriteLine(array(i)) Next Catch ex As Exception errormessage = ex.ToString() MsgBox(errormessage) Exit Sub Finally outpt.Close() End Try End Sub Open button: open file and read from it Private Sub btnopen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnopen.Click Dim input As streamreader Dim errormessage As String Dim i As Integer lstData.Items.Clear() Try input = File.OpenText("values.txt") 'could use dialog box or textbox for name For i = 0 To array.Length - 1 array(i) = CInt(input.ReadLine) lstData.Items.Add(array(i)) Next Catch ex As Exception errormessage = ex.ToString() MsgBox(ErrorMessage) Exit Sub Finally input.Close() End Try End Sub notes • Could have used a file dialog, or got filename(s) from the textbox. • Global array declared • Need to import system.io for streamreader and streamwriter Another streamreader example About this example • Streamreader can be opened from a string • Need imports System.io at the top of the application. • I first checked if the file existed, then displayed all the file contents Just the code for the open button Private Sub btnopen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnopen.Click Dim fname, line As String line = "“ ‘initialize the line to empty Dim strmreader As System.IO.StreamReader fname = txtfile.Text ‘get filename…a string If File.Exists(fname) Then ‘check if legal strmreader = System.IO.File.OpenText(fname) ‘note code here Do Until strmreader.Peek = -1’ and here…read to EOF line = strmreader.ReadLine ’streamreader can read a line lstdisplay.Items.Add(line) Loop Else MessageBox.Show("illegal file name") End If End Sub Reading individual characters: file contents 123 456 789 12 34 56 7 Display ASCII codes for chars Using read (instead of readline) Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim data As String Lstdisplay.Items.Clear() Dim sr As IO.StreamReader = IO.File.OpenText("C:\data.txt") Do While sr.Peek <> -1 data = sr.Read() 'read char by char Lstdisplay.Items.Add(data) Loop sr.Close() End Sub The stream methods Functions or subs may have optional arguments • • • • • • • • • • You can specify that a procedure argument is optional and does not have to be supplied when the procedure is called. Optional arguments are indicated by the Optional keyword in the procedure definition. The following rules apply: Every optional argument in the procedure definition must specify a default value. The default value for an optional argument must be a constant expression. Every argument following an optional argument in the procedure definition must also be optional. The following syntax shows a procedure declaration with an optional argument: Sub subname(ByVal arg1 As type1, Optional ByVal arg2 As type2 = default) Calling Procedures with Optional Arguments When you call a procedure with an optional argument, you can choose whether to supply the argument. If you do not, the procedure uses the default value declared for that argument. When you omit one or more optional arguments in the argument list, you use successive commas to mark their positions. The following example call supplies the first and fourth arguments but not the second or third: Call subname(arg1, , , arg4) ' Leaves out arg2 and arg3. compute degrees F or C based on which is passed Private Sub calc(Optional ByVal F As String = Nothing, Optional ByVal C As String = Nothing) Dim convert As Double Try If F Is Nothing Then ‘convert celsius temp to F Dim celsius As Double = CDbl(C) convert = 9 / 5 * celsius + 32 txtf.Text = convert.ToString("n2") Else ‘ must use F since C must be nothing Dim fahr As Double = CDbl(F) convert = 5 / 9 * (fahr - 32) txtc.Text = convert.ToString("n2") End If Catch ex As FormatException MessageBox.Show("at least on field must be a double") End Try End Sub Private Sub btnconvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnconvert.Click If txtf.Text = "" Then calc(, txtc.Text) Else calc(txtf.Text, ) End If End Sub Running optional args example Overloaded functions • A function “signature consists of the name, and parameters. • If function signatures differ (even though the names are the same), then VB, C++, VC++, java, etc, can distinguish which function you are trying to use. • So we could also code two versions of a given function. Function overloading: add ints, doubles and strings Function overload Private Sub btndostuff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndostuff.Click Dim s, t As String s = txtone.Text t = txttwo.Text txtint.Text = ADD(CInt(s), CInt(t)) txtdouble.Text = ADD(CDbl(s), CDbl(t)) txtstring.Text = ADD(s, t) End Sub Function ADD(ByVal s As String, ByVal t As String) As String ADD = s & t End Function Function ADD(ByVal s As Integer, ByVal t As Integer) As String ADD = (s + t).ToString End Function Function ADD(ByVal s As Double, ByVal t As Double) As String ADD = (s + t).ToString("n3") End Function