'------------------------------------------------------------- 'Lesson 3: L E A R N I N G A S P . N E T ' Ron Kessler ' C# 206 Class '------------------------------------------------------------- 'FEATURES: 'This beauty saves/gets one customer's information from "customers.txt" using streamreader/writer classes 'It shows how to get the default directory 'How to create a new test file in the application path 'How to close the browser using javascript 'Use the hyperlink control 'updated 3/24/08 for VS2005 Imports System.IO Partial Class _Default Inherits System.Web.UI.Page '---define path to customer file Dim rootPath As String = Server.MapPath("~") Dim FileName As String = rootPath & "\asp-customers.txt" #Region "Page Load" Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load '---this is a cool way to add a message box type function to a button on the web page. If Not IsPostBack Then Me.btnDone.Attributes.Add("onclick", "return confirm('Are you sure you want to quit?');") End If End Sub #End Region #Region "Create New File" Private Sub CreateFile() '---called from the btnSave_Click handler Dim MyWriter As StreamWriter = File.CreateText(FileName) MyWriter.Close() End Sub #End Region #Region "Save customer" Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click '---save/get one customers data Try If Not File.Exists(FileName) Then CreateFile() End If Using MyWriter As New StreamWriter(FileName) MyWriter.WriteLine(txtLast.Text) MyWriter.WriteLine(txtFirst.Text) MyWriter.Close() End Using Catch lblError.Visible = True End Try End Sub #End Region #Region "Cancel" Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click lblError.Visible = False txtFirst.Text = "" txtLast.Text = "" End Sub #End Region #Region "Get Customer" Protected Sub btnGet_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGet.Click Try Using myReader As New StreamReader(FileName) txtLast.Text = myReader.ReadLine txtFirst.Text = myReader.ReadLine myReader.Close() End Using Catch lblError.Text = "I can't read the data file." lblError.Visible = True End Try End Sub #End Region #Region "Purchase" Protected Sub btnBuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBuy.Click If Not File.Exists(rootPath & "\Streams.aspx") Then lblError.Text = "I can't find the Streams.aspx page." lblError.Visible = True Else '---navigate to the purchase page Response.Redirect("streams.aspx") End If End Sub #End Region #Region "Quit" Protected Sub btnDone_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDone.Click '---close the browser Response.Write("") End Sub #End Region End Class