Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 13 Exploring Text Files and String Processing 339


For i = 0 To charsInFile - 1
letter = txtNote.Text.Substring(i, 1)
'determine ASCII code and add one to it
Encrypt = Encrypt & Chr(Asc(letter) + 1)
Next
'write encrypted text to file
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, Encrypt, False)
txtNote.Text = Encrypt
txtNote.Select(0, 0) 'remove text selection
mnuCloseItem.Enabled = True
Catch ex As Exception
MsgBox("An error occurred." & vbCrLf & ex.Message)
End Try
End If
Note especially the statement:

Encrypt = Encrypt & Chr(Asc(letter) + 1)
which determines the ASCII code of the current letter, adds 1 to it, converts the ASCII
code back to a letter, and then adds it to the Encrypt string.


  1. Now display the mnuOpenItem_Click event procedure in the Code Editor to see how
    the program reverses the encryption.
    This program code is nearly identical to that of the Save Encrypted File As command,
    but rather than adding 1 to the ASCII code for each letter, it subtracts 1. Here’s the
    complete mnuOpenItem_Click event procedure, with noteworthy statements in bold:
    Dim AllText As String
    Dim i, charsInFile As Short
    Dim letter As Char
    Dim Decrypt As String = ""


OpenFileDialog1.Filter = "Text files (*.txt)|*.txt"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then 'display Open dialog box
If My.Computer.FileSystem.FileExists(OpenFileDialog1.FileName) Then
Try 'open file and trap any errors using handler
AllText = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
'now, decrypt string by subtracting one from ASCII code
charsInFile = AllText.Length 'get length of string
For i = 0 To charsInFile - 1 'loop once for each char
letter = AllText.Substring(i, 1) 'get character
Decrypt = Decrypt & Chr(Asc(letter) - 1) 'subtract 1
Next i 'and build new string
txtNote.Text = Decrypt 'then display converted string
lblNote.Text = OpenFileDialog1.FileName
txtNote.Select(0, 0) 'remove text selection
txtNote.Enabled = True 'allow text cursor
mnuCloseItem.Enabled = True 'enable Close command
mnuOpenItem.Enabled = False 'disable Open command
Catch ex As Exception
MsgBox("An error occurred." & vbCrLf & ex.Message)
End Try
End If
End If
Free download pdf