Visual Basic 2008 comes with a lot of predefined code snippets for selected actions, and you can insert these snippets in your code as needed. Let’s say you want to insert the statements for writing some text to a file, but you have no idea how to access files. Create an empty line in the listing (press the Enter key a couple of times at the end of a code line). Then open the Edit menu and choose IntelliSense > Insert Snippet (or right-click somewhere in the code window and choose Insert Snippet from the context menu).
You will see on the screen a list of the snippets, organized in folders according to their function, as shown in Figure 1.17. Select the fundamentals folder, which will display another list of options: collections and arrays, datatypes, filesystem, and math. Double-click the filesystem item to see a list of common file-related tasks, as shown in Figure 1.18. Locate the item Write Text To A File in the list and double-click it to insert the appropriate snippet at the current location in the code window.
Figure 1.17 – Code Snippets in Visual Basic 2008
The following snippet will be inserted in your code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Code language: VB.NET (vbnet)
To write some text to a file, you need to call the WriteAllText method of the My.Computer .FileSystem object. You can replace the strings shown in the snippet with actual values. The first string is the filename, the second string is the text to be written to the file, and the last argument of the method determines whether the text will be appended to the file (if False) or will overwrite any existing text (if True).
Figure 1.18 – Selecting a Code Snippet in Visual Basic 2008
The snippet shows you the basic statements for performing a common task, and you can edit the code inserted by Visual Studio as needed. A real-world application would probably prompt the user for a filename via the File common dialog box and then use the filename specified by the user in the dialog box, instead of a hard-coded file name.
As you program, you should always try to find out whether there’s a snippet for the task at hand. Sometimes you can use a snippet without even knowing how it works. Although snippets can simplify your life, they won’t help you understand the Framework, which is discussed in detail throughout this tutorial.