mobile_io

advertisement
File IO differs on the CE platform. This short [rpgram simply creates a file for writing, writes a
line, saves the contents and closes. The Reader oens the released file and sends the text to the
text box.
In the form designer grab a text box, make it multiline and opalce a button on the form as well.
Imports System.IO
Imports System.Text
Public Class Form1
Dim pth As String =
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetNa
me().CodeBase)
Dim fileName As String = Path.Combine(pth, "cool.txt")
Dim sw As IO.StreamWriter
Dim sr As IO.StreamReader
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Try
'open file
sw = File.CreateText(fileName)
sw.WriteLine("hello word")
sw.Close()
sr = File.OpenText(fileName)
While sr.Peek <> -1
TextBox1.Text = sr.ReadLine
End While
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
sr.Close()
End Try
End Sub
End Class
Now we could add a panel and a second buttion, one for writing.:
Imports System.IO
Imports System.Text
1
Public Class Form1
Dim pth As String =
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetNa
me().CodeBase)
Dim fileName As String = Path.Combine(pth, "cool.txt")
Dim sw As IO.StreamWriter
Dim sr As IO.StreamReader
Dim isthere As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
If File.Exists(fileName) Then
isthere = True
Else
sw = File.CreateText(fileName)
sw.Close()
End If
Panel1.Controls.Add(TextBox1)
Panel1.Controls.Add(Button1)
Panel1.Controls.Add(Button2)
End Sub
Private Sub OpenButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Try
'open file
sr = File.OpenText(fileName)
While sr.Peek <> -1
TextBox1.Text = sr.ReadToEnd
End While
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
sr.Close()
End Try
Panel1.BringToFront()
Panel1.Enabled = True
End Sub
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Try
sw = File.CreateText(fileName)
sw.WriteLine(TextBox1.Text())
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
sw.Close()
End Try
Panel1.BringToFront()
2
Panel1.Enabled = True
End Sub
End Class
Finally a SaveDialog and an OpenDialog make it even better. We have mmanaged to re-invent
notepad!
For the button on the save event, add the following changes to your code:
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.FilterIndex = 2
SaveFileDialog1.ShowDialog()
Try
fileName = SaveFileDialog1.FileName
sw = File.CreateText(fileName)
(download the entire code from http://munro.humber.ca/~dymond/mobile/notepad.zip
Adding advanced file format saving can be invoked by adding a menu with sub menu items to
the dialog. With this option Unicode, ASCII, UTF-7 and UTF-8 are supported.
Private Sub mitemFileFormat_Click( _
ByVal sender As Object, _
ByVal e As EventArgs _
) _
Handles mitemFFAscii.Click, _
mitemFFDefault.Click, _
mitemFFUnicode.Click, _
mitemFFUtf7.Click, _
mitemFFUtf8.Click
If sender.Equals(mitemFFAscii) Then
Me.encodeFile = Encoding.ASCII
ElseIf sender.Equals(mitemFFUnicode) Then
Me.encodeFile = Encoding.Unicode
ElseIf sender.Equals(mitemFFUtf7) Then
Me.encodeFile = Encoding.UTF7
ElseIf sender.Equals(mitemFFUtf8) Then
Me.encodeFile = Encoding.UTF8
Else
Me.encodeFile = Encoding.Default
End If
End Sub
The Money class below represents revenue and expenditure transactions in a common format.
With that in mind, a list of these objects can be populated from a delimited file. Our file needs to
have entries for titles, dates and amounts. The data typing will be different for each so a property
class is in order.
3
Public Class Money
Dim tl As String
Dim expDate As Date
Dim amt As Double
Public Sub New()
Title = ""
expDate = Now
amt = 0
End Sub
Public Sub New(ByVal _tl As String, ByVal _expDate As Date, ByVal _amt As
Double)
tl = _tl
expDate = _expDate
amt = _amt
End Sub
Public Property Title()
Get
Return tl
End Get
Set(ByVal value)
tl = value
End Set
End Property
Public Property moneyDate()
Get
Return expDate
End Get
Set(ByVal value)
expDate = value
End Set
End Property
Public Property moneyAmount()
Get
Return amt
End Get
Set(ByVal value)
amt = value
End Set
End Property
End Class
Getting text or any file from a disc requires a some mapping of the applications context. We will
also need a file name, a writer (for appending) and a reader for rendering.
We now want to read data from the file and hand those values off to the properties in a new
instance of our Money class, see below:
Imports System.IO
4
Imports System.Text
Public Class MoneyFileMgr
Dim pth As String =
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetNa
me().CodeBase)
Dim fileName As String = Path.Combine(pth, "MoneyFile.txt")
Dim sw As IO.StreamWriter
Dim sr As IO.StreamReader
Public Sub New()
End Sub
'check if file exists
Public Function doesFileExist() As Boolean
If File.Exists(fileName) Then
Return True
Else
Return False
End If
End Function
'return all Money records from the textfile
Public Function getMoneys() As List(Of Money)
Dim li As New List(Of Money)
Try
'open file
sr = File.OpenText(fileName)
While sr.Peek <> -1
'read data from text file
Dim arr() As String = sr.ReadLine.Split(":")
'create Money object
Dim exp As New Money
exp.MoneyDate = CDate(arr(0))
exp.Title = arr(1)
exp.MoneyAmount = CDbl(arr(2))
'add money object to list
li.Add(exp)
End While
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
sr.Close()
End Try
Return li
End Function
'write money reaocrds to text file
Public Function writeMoneys(ByVal li As List(Of Money)) As Boolean
Try
'overwrite money file
sw = File.CreateText(fileName)
'loop thru all moneys
For Each exp As Money In li
Dim sb As New StringBuilder
sb.Append(CStr(exp.moneyDate))
5
sb.Append(":")
sb.Append(exp.Title)
sb.Append(":")
sb.Append(exp.moneyAmount.ToString())
sw.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
sw.Close()
End Try
End Function
End Class
Try employing and assigning the values to controls in a small project. (exercise)
Look at the hangamn application that we began last week. How could we save state, thaqt is
return to abondoned games? Could we also track user scores to see who did the best (fewest
wrong guesses) by username? Finally, a text file would be an ideal place to store the words that
are at the heart of the game. How could that be acoomplished?
Leading into next week, this short program uses a simple business object to populate the fileds in
a table bound to a datagrid. The program is a simple introduction to datasources and databinding.
Imports System.Data
Imports System.Xml
Imports System.IO
Public Class Form1
Dim pth As String =
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetNa
me().CodeBase)
Dim fileName As String = Path.Combine(pth, "news.xml")
Function CreateDataSource() As ICollection
' its kind cool how we can create data representations without a database
‘this is done with an object datsource in ASP and Web Services
Dim dt As DataTable
dt = New DataTable()
Dim dr As DataRow
dt.Columns.Add(New DataColumn("Company"))
'the column names will act as identifiers for the repeater below
dt.Columns.Add(New DataColumn("Website"))
'now we need some info for the rows
dr = dt.NewRow()
6
'dr.
dr(0) = "
Microsoft
"
dr(1) = "http://www.microsoft.com"
'add the row to the table
dt.Rows.Add(dr)
'now set up a new row
dr = dt.NewRow()
'add the items for each column
dr(0) = "I.B.M."
dr(1) = "http://www.ibm.com"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr(0) = "Oracle"
dr(1) = "http://www.oracle.com"
dt.Rows.Add(dr)
'we need a data view for the repeater so...
Dim dv As DataView
dt.TableName = "NEWS"
dv = New DataView(dt)
CreateDataSource = dv
End Function
‘handle the load and bind the data at the same time, maybe a different event
‘would be more natural?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
DataGrid1.DataSource = CreateDataSource()
End Sub
End Class
7
Download