Defensive coding practices - check inputs
Something which, although I knew a bit about through my scant knowledge of using the Command line, had never really dawned up me. I created 2 files called "File.txt" and put them into the following locations:
- C:\SafeScripts\File.txt
- C:\File.txt
The contents of the first file was the text "I am good" and the contents of the second file were "I am evil"; have a guess what gets displayed when I run the following code:
Private Const SAFE_PATH As String = "C:\SafeScripts\" Private Sub MyForm_Load( ... ) ' supplied from user Dim niceFile As String = TextBox1.Text ' user enters "..\File.txt" Label1.Text = ReadFromFile( niceFile ) End Sub Private Function ReadFromFile( ByVal niceFile As String ) As String Dim fullPath As String = IO.Path.Combine( SAFE_PATH, niceFile ) Dim fs As FileStream = File.OpenRead( fullpath ) Dim sr As StreamReader = New StreamReader( fs ) ReadFromFile = sr.ReadToEnd sr.Close() fs.Close() End Function
Yep, you guessed it: "I am evil". Nothing really earth shattering here, but a useful reminder to practice defensive coding practices :-)