342 Part II Programming Fundamentals
The program opens the file and restores the text by using the Xor operator and the
encryption code you specified.
- On the File menu, click the Exit command to end the program.
Examining the Encryption Program Code
The Xor operator is used in both the mnuSaveAsItem_Click and the mnuOpenItem_Click event
procedures. By now, these generic menu processing routines will be fairly familiar to you. The
mnuSaveAsItem_Click event procedure consists of these program statements (noteworthy
lines in bold):
Dim letter As Char
Dim strCode As String
Dim i, charsInFile, Code As Short
Dim StreamToWrite As StreamWriter = Nothing
SaveFileDialog1.Filter = "Text files (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
Try
strCode = InputBox("Enter Encryption Code")
If strCode = "" Then Exit Sub 'if cancel clicked
'save text with encryption scheme
Code = CShort(strCode)
charsInFile = txtNote.Text.Length
StreamToWrite = My.Computer.FileSystem.OpenTextFileWriter( _
SaveFileDialog1.FileName, False)
For i = 0 To charsInFile - 1
letter = txtNote.Text.Substring(i, 1)
'convert to number w/ Asc, then use Xor to encrypt
StreamToWrite.Write(Asc(letter) Xor Code) 'and save in file
'separate numbers with a space
StreamToWrite.Write(" ")
Next
mnuCloseItem.Enabled = True
Catch ex As Exception