vb file processing n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
VB File Processing PowerPoint Presentation
Download Presentation
VB File Processing

Loading in 2 Seconds...

play fullscreen
1 / 47

VB File Processing - PowerPoint PPT Presentation


  • 343 Views
  • Uploaded on

VB File Processing. The Process of Using a File . The file must be opened. Data is either written to the file or read from the file. When the application is finished using the file, the file is closed. Types of Text File. Sequential text file HTML file, Email file, etc.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'VB File Processing' - zuriel


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
the process of using a file
The Process of Using a File
  • The file must be opened.
  • Data is either written to the file or read from the file.
  • When the application is finished using the file, the file is closed.
types of text file
Types of Text File
  • Sequential text file
    • HTML file, Email file, etc.
  • Comma-Delimited file
    • "s5","peter",3.5
    • "s1","paul",3
    • "s7","mary",2
  • Random access file
slide4

x-sender: me@dchaolaptop

x-receiver: you@dchaolaptop

Received: from mail pickup service by dchaolaptop with Microsoft SMTPSVC;

Mon, 19 May 2003 11:27:02 -0700

From: <me>

To: <you@dchaolaptop>

Subject: testReply6

Date: Mon, 19 May 2003 11:27:01 -0700

Message-ID: <008e01c31e34$3d982660$0100007f@dchaolaptop>

MIME-Version: 1.0

Content-Type: text/plain; charset="iso-8859-1"

Content-Transfer-Encoding: 7bit

X-Mailer: Microsoft CDO for Windows 2000

Thread-Index: AcMeND2WJSRAs2TDR6WvOdKh/HDlHA==

Content-Class: urn:content-classes:message

X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000

X-OriginalArrivalTime: 19 May 2003 18:27:02.0053 (UTC) FILETIME=[3DCDB550:01C31E34]

testreplyreply6

system io namespace
System.IO Namespace
  • Directory
  • File
  • StreamReader
  • StreamWriter
  • StringReader
  • StringWriter
stream
Stream
  • A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. The Stream class and its derived classes provide a generic view of these different types of input and output, isolating the programmer from the specific details of the operating system and the underlying devices.
creating a sequential text file
Creating a Sequential Text File
  • Declare a System.IO.StreamWriter writer object:
    • Dim myFile As System.IO.StreamWriter
  • Create a file using System.IO.File.CreateText or AppendText method.
    • myFile=system.IO.File.CreateText(“c:\myTextFile.txt”)
      • CreateText method returns a StreamWriter.
      • If myTextFile.txt already exist, its contents will be erased
    • myFile=system.IO.File. AppendText(“c:\myTextFile.txt”)
      • If myTextFile.txt already exist, data will be appended to the end.
      • Note: CreateText and AppendText return a StreamWriter object.
  • Use writer object’s WriteLine method to write data.
    • myFile.WriteLine(“test”) ***create a new line
    • myFile.Write(“test”) ***does not create a new line
  • Use writer object’s Close method to close the file.
    • myFile.Close()
creating a text file
Creating a Text File

Imports System.IO

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim myFile As System.IO.StreamWriter

myFile = System.IO.File.CreateText("c:\myTextFile.txt")

myFile.Write(TextBox1.Text)

myFile.Close()

End Sub

reading files with streamreader
Reading Files with StreamReader
  • Declare a System.IO.StreamReader reader object:
    • Dim myFile As System.IO.StreamReader
  • Open the file using System.IO.File.OpenText method.
    • myFile=system.IO.File.OpenText(“c:\myTextFile.txt”)
      • Use system.IO.File.Exists(FileName) to test if file exists.
  • Read Data
    • myFile.ReadLine() *** Read one line
    • myFile.Read() *** Read one character code. Use Chr function to convert the code to character: chr(myFile.Read())
      • ReadLine and Read methods automatically move the pointer.
      • To detect the end of a file: MyFile.Peek=-1
    • myFile.ReadToEnd() *** read entire contents of a file.
  • Use writer object’s Close method to close the file.
    • myFile.Close()
reading a text file
Reading a Text File

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim myFile As System.IO.StreamReader

myFile = System.IO.File.OpenText("c:\myTextFile.txt")

TextBox1.Text = myFile.ReadToEnd()

myFile.Close()

End Sub

openfiledialog
OpenFileDialog
  • Properties
    • Filter: description|filter
      • The description and the filter are separated with the pipe | symbol.
        • Text file (*.txt) | *.txt
        • All files (*.*) | *.*
    • Initial directory
    • FileName
  • Method:
    • ShowDialog
openfiledialog example
OpenFileDialog Example

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then

MessageBox.Show(OpenFileDialog1.FileName)

myFile = System.IO.File.OpenText(OpenFileDialog1.FileName)

TextBox1.Text = myFile.ReadToEnd

Else

MsgBox("no file selected")

End If

savefiledialog example
SaveFileDialog Example

Dim outFile As System.IO.StreamWriter

If documentName = "" Then

If saveFileDialog1.ShowDialog = DialogResult.OK Then

documentName = saveFileDialog1.FileName

End If

End If

outFile = System.IO.File.CreateText(documentName)

outFile.Write(TextBox1.Text)

outFile.Close()

drawstring print one line of text
DrawString: Print One Line of Text
  • System.Drawing.Graphics
    • DrawString method arguments:
        • String to print
        • Font
        • Brush
        • X position
        • Y position
  • The X, Y coordinates must be declared as Single data type. X coordinate is the horizontal distance across a line from the left edge, Y coordinate is the distance from the top.
printdocument control
PrintDocument Control
  • PrinterSetting property:
    • PrinterName
    • PrintToFile
    • MaximumPage
    • MinimumPage
    • PaperSize
  • Method:
    • Print *** The Print method will trigger the PrintPage event
printdialog control
PrintDialog Control
  • Use the PrintDialog to get the values for the PrinterSetting property of the PrintDocument control.
    • PrintDialog1.Document = PrintDocument1
    • PrintDialog1.ShowDialog()
    • With PrintDocument1.PrinterSettings
    • .PrintToFile = PrintDialog1.PrinterSettings.PrintToFile
    • .MaximumPage = PrintDialog1.PrinterSettings.MaximumPage
    • .PrinterName = PrintDialog1.PrinterSettings.PrinterName
    • End With
  • Note: The PrintDialog’s Document property gets or sets a value indicating the PrintDocument used to obtain PrinterSetting.
printdocument example
PrintDocument Example

PrintDocument1.Print()

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

e.Graphics.DrawString(textbox1.text, New Font("courier", 18, FontStyle.Bold), Brushes.Black, 150, 80)

End Sub

print and printpage event
Print and PrintPage Event
  • The Print method of the PrintDocument control will trigger the PrintPage event. This event is fired once for each page to be printed. After finishing printing one page, we can use the PrintPageEventArgs’ HasMorePage property to inform the PrintDocument whether there is more page to print.
printpreviewdialog control
PrintPreviewDialog Control
  • PrintPreviewDialog1.Document = PrintDocument1
  • PrintPreviewDialog1.ShowDialog()
print multiple lines
Print Multiple Lines
  • Textbox’s MultiLine property is true.
  • Textbox’s Lines property returns a string array with each line as an element.
  • The Y position must be increased by the height of the font.
printpageeventargs
PrintPageEventArgs
  • DrawString: Send a line of text to the graphics page.
  • Properties:
    • MarginBounds.Left, top, bottom, etc.
    • HasMorePage
slide22

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

Dim fntPrintFont As New Font("Courier", 18)

Dim sngLineHeight As Single = fntPrintFont.GetHeight + 2

Dim sngXPos As Single = e.MarginBounds.Left

Dim sngYPos As Single = e.MarginBounds.Top

Dim tempArray() As String

tempArray = TextBox1.Lines

Dim line As Integer

For line = 0 To tempArray.GetUpperBound(0)

e.Graphics.DrawString(tempArray(line), fntPrintFont, Brushes.Black, sngXPos, sngYPos)

sngYPos += sngLineHeight

Next

End Sub

printing multiple pages
Printing Multiple Pages

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

Static pageCount As Integer = 1

Static lineCount As Integer = 0

Dim fntPrintFont As New Font("Courier", 18)

Dim sngLineHeight As Single = fntPrintFont.GetHeight + 2

Dim sngXPos As Single = e.MarginBounds.Left

Dim sngYPos As Single = e.MarginBounds.Top

Dim counter As Integer

Dim tempArray() As String

tempArray = TextBox1.Lines

e.Graphics.DrawString("Page " & pageCount.ToString, fntPrintFont, Brushes.Black, sngXPos, sngYPos)

sngYPos += sngLineHeight

For counter = lineCount To tempArray.GetUpperBound(0)

e.Graphics.DrawString(tempArray(counter), fntPrintFont, Brushes.Black, sngXPos, sngYPos)

sngYPos += sngLineHeight

If sngYPos >= e.MarginBounds.Bottom Then

pageCount = pageCount + 1

lineCount = counter + 1

e.HasMorePages = True

Exit For

End If

Next

End Sub

a few notes
A Few Notes
  • The X, Y coordinates must be declared as Single data type. X coordinate is the horizontal distance across a line from the left edge, Y coordinate is the distance from the top.
  • Font object type and its properties and methods.
  • Textbox’s Lines property returns a string array with each line as an element.
  • Why the pageCount and lineCount are declared as Static?
comma delimited file
Comma-Delimited File
  • It stores each data item with a comma separating each item and places double quotes around string fields.
    • “S5”, ”Peter”, 3.0
    • “S1”, “Paul”, 2.5
creating a comma delimted file
Creating a Comma-Delimted File
  • Imports System.IO
  • Open the file for output:
    • fileNumber = FreeFile()
    • FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Output)
      • Note: FreeFile function returns a file number.
  • Use WriteLine function to write a record to the file:
    • WriteLine(fileNumber, TextBox1.Text, TextBox2.Text, CDbl(TextBox3.Text))
      • Note: Assuming write a student record with CID, CNAme, and GPA fields.
  • Use the FileCose function to close the file:
    • FileClose(fileNumber)
  • Note: OpenMode.Append
reading a comma delimted file
Reading a Comma-Delimted File
  • Imports System.IO
  • Open the file for input:
    • fileNumber = FreeFile()
    • FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Input)
  • Use Input function to read a field from the file:
    • If Not EOF(fileNumber) Then
    • Input(fileNumber, TextBox1.Text)
    • Input(fileNumber, TextBox2.Text)
    • Input(fileNumber, TextBox3.Text)
    • Else
    • MsgBox("Reach EOF")
    • End If
      • Note: The Input function can read only one filed from the file at a time.
      • Note: The EOF function detects the End of File condition.
  • Use the FileCose function to close the file:
    • FileClose(fileNumber)
sequentialy accessing the student file to compute average gpa
Sequentialy Accessing the Student File to Compute Average GPA

Dim fileNumber, stCounter As Integer

Dim temp1, temp2 As String

Dim gpa, sumGpa As Double

fileNumber = FreeFile()

FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Input)

Do While Not EOF(fileNumber)

Input(fileNumber, temp1)

Input(fileNumber, temp2)

Input(fileNumber, gpa)

sumGpa += gpa

stCounter += 1

Loop

MessageBox.Show(sumGpa / stCounter.ToString)

create a file processing application
Create a File Processing Application
  • Use a form to display a customer record in textboxes. This form has a MoveNext button to show the next record.
  • A form to enter new customer data.
structures
Structures
  • A user-defined data type to hold related fields.
    • Structure emp
    • Dim eid As String
    • Dim ename As String
    • Dim salary As Double
    • End Structure
    • Dim myEmp as emp
    • myEmp.eid=“e1”
    • myEmp.ename=“peter”
    • myEmp.salary=5000.00
slide31
A structure may contain arrays as fields, but cannot be declared with an initial size. Must use a ReDim statement to declare the size. Structure emp
    • Dim eid As String
    • Dim ename As String
    • Dim salary As Double
    • Dim dependent() As String
    • End Structure
    • Dim myEmp as emp
    • ReDim myEmp.dependent(3)
slide32
A structure may also contain methods.
    • Structure emp
    • Dim eid As String
    • Dim ename As String
    • Dim salary As Double
    • Dim dependent() As String
    • Function tax(ByVal salary) As Double
    • tax = salary * 0.15
    • End Function
    • End Structure
    • Dim myEmp As emp
    • myEmp.salary = 1000
    • myEmp.tax(myEmp.salary)
random access file
Random-Access File
  • Records in a random-access file do not have to processed in sequence. A record can be retrieved selectively.
  • A random-access file can be opened for both reading and writing.
  • Each record in a random-a ccess file is identified by a unique integer, the first record is record 1.
  • The records in a random-access file must be the same size.
using a structure to create record
Using a Structure to Create Record
  • Structure emp
  • <VBFixedString(3)> Dim eid As String
  • <VBFixedString(10)> Dim ename As String
  • Dim salary As Double
  • Function tax(ByVal salary) As Double
  • tax = salary * 0.15
  • End Function
  • End Structure
  • Note: Use <VBFixedString(3)> to control string size.
opening a random access file
Opening a Random-Access File
  • FileOpen(fileNumber, fileName,OpenMode,OpenAccess, OpenShare, RecordLength)
  • OpenMode: Random
  • OpenAccess:ReadWrite
  • OpenShare
  • RecordLength
  • Example:
    • Dim MyEmp as Emp
    • fileNumber = FreeFile()
    • FileOpen(fileNumber, "c:\empRnd.txt", OpenMode.Random, OpenAccess.ReadWrite, OpenShare.Default, Len(myEmp))
writing a record
Writing a Record
  • FilePut(FileNumber, Record, RecordNumber)
    • myEmp.eid = TextBox1.Text
    • myEmp.ename = TextBox2.Text
    • myEmp.salary = CDbl(TextBox3.Text)
    • FilePut(fileNumber, myEmp, CInt(myEmp.eid.Substring(1)))

Note: Assuming EID is of this format: XNN.

reading a record
Reading a Record
  • FileGet(FileNumber, Record, RecordNumber)
    • Dim recNumber As Integer
    • recNumber = CInt(InputBox("Please enter empID: ").Substring(1))
    • FileGet(fileNumber, myEmp, recNumber)
    • TextBox1.Text = myEmp.eid
    • TextBox2.Text = myEmp.ename
    • TextBox3.Text = myEmp.salary.ToString
random file example
Random File Example

Dim fileNumber As Integer

Structure emp

<VBFixedString(3)> Dim eid As String

<VBFixedString(10)> Dim ename As String

Dim salary As Double

Function tax(ByVal salary) As Double

tax = salary * 0.15

End Function

End Structure

Dim myEmp As emp

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

fileNumber = FreeFile()

FileOpen(fileNumber, "c:\empRnd.txt", OpenMode.Random, OpenAccess.ReadWrite, OpenShare.Default, Len(myEmp))

writing and reading
Writing and Reading

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

myEmp.eid = TextBox1.Text

myEmp.ename = TextBox2.Text

myEmp.salary = CDbl(TextBox3.Text)

FilePut(fileNumber, myEmp, CInt(myEmp.eid.Substring(1)))

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim recNumber As Integer

recNumber = CInt(InputBox("Please enter empID: ").Substring(1))

FileGet(fileNumber, myEmp, recNumber)

If myEmp.eid.Substring(0, 1) <> "e" Then

MsgBox("record not exist")

Else

TextBox1.Text = myEmp.eid

TextBox2.Text = myEmp.ename

TextBox3.Text = myEmp.salary.ToString

End If

End Sub

sequential access to a random access file
Sequential Access to a Random-Access File

Dim outString As String

Dim recNumber As Integer = 1

Do While Not EOF(fileNumber)

FileGet(fileNumber, myEmp, recNumber)

outString = outString & recNumber.ToString & myEmp.eid & myEmp.ename & myEmp.salary.ToString & vbCrLf

recNumber += 1

Loop

MessageBox.Show(outString)

Note: Do While recNumber <= NumberOfRecords

hashing
Hashing
  • RecordAddress = H(Key)
  • H(Key)=Key Mod M

0 <= Key Mod M <= M – 1

1 <= 1 + Key Mod M <= M

hashing example
Hashing Example
  • Key Mod 8
    • H(1821) = 5
    • H(7115) = 3
    • H(2428) = 4
    • H(4750) = 6
    • H(1620) = 4 **** Collision
    • H(4692) = 4
    • H(4758) = 6
  • Collision resolution:
    • Linear probing
inserting a record
Inserting a Record
  • H(Key)
  • If space H(Key) available, insert into space K(Key)
  • Else check subsequent space until a free space is found.
    • *** How to detect the file is full?
searching a record
Searching a Record
  • Read record at H(Key)
  • If no record at H(Key), then record not exist
  • If record at H(Key) is the searched record, then Found
  • Else Search the next space until reach an empty space.
deleting a record
Deleting a Record
  • Search the record to be deleted.
  • Change a field to a special deletion flag.
  • Write it back to its original space with the deletion flag.
serialization
Serialization
  • The act of saving (serializing) an object onto a storage medium and later deserializing it from the storage medium to recreate an object.
  • BinaryFormatter:
    • Serialize
    • Deserialize
slide47

Imports System.IO

Imports System.Runtime.Serialization.Formatters.Binary

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim fs As New FileStream("c:\testSerializing.dat", FileMode.Create)

Dim myArrayList As New ArrayList

myArrayList.Add("A")

myArrayList.Add("B")

myArrayList.Add(5)

myArrayList.Add(10)

Dim bf As New BinaryFormatter

bf.Serialize(fs, myArrayList)

fs.Close()

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim fs As New FileStream("c:\testSerializing.dat", FileMode.Open)

Dim myArrayList As New ArrayList

Dim bf As New BinaryFormatter

myArrayList = CType(bf.Deserialize(fs), ArrayList)

Dim obj As New Object

For Each obj In myArrayList

ListBox1.Items.Add(obj)

Next

End Sub