Build Your Own ASP.NET 3.5 Website Using C# & VB (103 page)

Read Build Your Own ASP.NET 3.5 Website Using C# & VB Online

Authors: Cristian Darie,Zak Ruvalcaba,Wyatt Barnett

Tags: #C♯ (Computer program language), #Active server pages, #Programming Languages, #C#, #Web Page Design, #Computers, #Web site development, #internet programming, #General, #C? (Computer program language), #Internet, #Visual BASIC, #Microsoft Visual BASIC, #Application Development, #Microsoft .NET Framework

BOOK: Build Your Own ASP.NET 3.5 Website Using C# & VB
13.41Mb size Format: txt, pdf, ePub

Working with Files and Email

599

Figure 14.1. Disabling simple file sharing in Windows XP

6.

Select the new user in the list, and click on the
Write
checkbox under
Allow
in

the permissions list, as shown in Figure 14.3.

7.

Click
OK
.

Figure 14.3. Giving write access to ASPNET

Licensed to [email protected]

600

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Writing Content to a Text File

For the purposes of the next few exercises, let’s work again with our old friend, the

LearningASP
folder. Start Visual Web Developer, open the
LearningASP\CS
or

LearningASP\VB
folder, and create a new web form called
WriteFile.aspx
. Make

sure you
aren’t
using a code-behind file or a master page. Next, enter the code shown here in bold:

LearningASP\VB\WriteFile_1.aspx
(excerpt)

<%@ Page Language="VB" %>

<%@ Import Namespace="System.IO" %>

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




<br/><b>Writing to Text Files<br/></b>





Write the following text within a text file:



OnClick="WriteText" />





As you can see, we import the System.IO namespace—the namespace that contains

the classes for working with text files—first. Next, we add a TextBox control to

handle collection of the user-entered text, and a Button control to send the information to the server for processing. Licensed to [email protected]

Working with Files and Email

601

Next, in the tag, we’ll create the WriteText method mentioned in the OnClick

attribute of the Button. This method will write the contents of the TextBox to the

text file:

Visual Basic

LearningASP\VB\WriteFile_2.aspx
(excerpt)


C#

LearningASP\CS\WriteFile_2.aspx
(excerpt)


Apart from the new Using construct, the code is fairly straightforward. First, we

create a StreamWriter variable called streamWriter. To obtain the variable’s value,

we call the CreateText method of the File class, passing in the location of the text

file, which returns a new StreamWriter. Don’t forget that C# needs to escape backslashes when they’re used in strings, so the path to our file must use \\ to separate folder names, or use the @ character in front of the string so that backslashes are

automatically ignored.

What about Using, then? Similarly to database connections, streams are something

that we need to close when we’re finished working with them, so they don’t occupy

resources unnecessarily. The Using construct is a common means of ensuring that

the stream is closed and
disposed of
after we work with it.

Licensed to [email protected]

602

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Disposing of Objects

Technically, when we work with Using, the object is disposed of, rather than

simply closed. The action is identical to explicitly calling its Dispose method.

When the code enclosed by Using finishes executing, streamWriter’s Dispose

method is called automatically for you. This ensures that it doesn't keep any resources locked, and that
the object itself
is removed from memory immediately. In the world of .NET, closed objects are cleared from memory at regular intervals

by .NET’s Garbage Collector, but for classes that support the Dispose method

(such as StreamWriter), you can use this method (or the Using construct) to

remove an object from memory immediately.

It’s also interesting to note the way we used the File class’s CreateText method

in the code above. Normally, when we need to call a method of a particular class,

we create an object of that class first. How was it possible to call the CreateText

method using a class name, without creating an object of the File class first?

The CreateText method is what Visual Basic calls a
shared method
, and what’s

known in C# as a
static method
. Shared or static methods can be called without our

having to create an actual instance of the class. In the above code, CreateText is a

shared or static method, because we can call it directly from the File class, without

having to create an instance of that class.

We worked with shared/static class members earlier, when we read the connection

string. In that case, you didn’t need to create an object of the ConfigurationManager

class in order to read your connection string:

Visual Basic

string connectionString =

ConfigurationManager.ConnectionStrings( _

"Dorknozzle").ConnectionString

Instance methods
, on the other hand, are those with which you’re familiar—they

may only be called on an instance (object) of the class. Instance methods are most

commonly used, but shared/static methods can be useful for providing generic

functionality that doesn’t need to be tied to a particular class instance.

Licensed to [email protected]

Working with Files and Email

603

Now, test the page in your browser. Initially, all you’ll see is an interface that’s

similar to
Figure 14.4
.

Type some text into the text box, and click the
Write
button to submit your text for

processing. Browse to and open the
C:\LearningASP\VB\myText.txt
or
C:\Learnin-

gASP\CS\myText.txt
file in Notepad, and as in Figure 14.5, you
’ll see the newly added text.

If you try to enter a different value into the TextBox control and click the
Write

button, the existing text will be overwritten with the new content. To prevent this

from happening, you can replace the call to the CreateText method with a call to

AppendText. As
Figure 14.6
shows, the AppendText method adds to existing text, rather than replacing it.

Figure 14.6. Appending text

Also note that, rather than specifying the full path to the text file, you can use the

MapPath method to generate the full path to the text file automatically. All you need

to do is give the method a path that’s relative to the current directory, as follows:

Visual Basic

LearningASP\VB\WriteFile_3.aspx
(excerpt)

Using streamWriter As StreamWriter = File.AppendText( _

MapPath("myText.txt")
)

C#

LearningASP\CS\WriteFile_3.aspx
(excerpt)

using (StreamWriter streamWriter = File.AppendText(

MapPath("myText.txt")
))

Licensed to [email protected]

604

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Figure 14.4. Writing text to a file

Figure 14.5. Viewing your new file in Notepad

The MapPath method returns the full path to the filename that you pass in as a

parameter, and can make for cleaner code that’s easier to read.

Reading Content from a Text File

Just as you used the CreateText and AppendText methods of the File class to return

a new StreamWriter object, you can use the OpenText method of the File class to

return a new StreamReader. Once the StreamReader has been established, you can

loop through the text file using a While loop in conjunction with the object’s

ReadLine method to examine the contents of the text file.

To experiment with the process of reading from text files, create a new web form

named
ReadFile.aspx
in the same way that you created
WriteFile.aspx
, and add this code to it:

Other books

Just 2 Seconds by Gavin de Becker, Thomas A. Taylor, Jeff Marquart
The Einstein Papers by Craig Dirgo
Shiverton Hall by Emerald Fennell
Ipods in Accra by Sophia Acheampong
A Whisper to the Living by Ruth Hamilton
Katsugami by Debbie Olive
My Name Is Leon by Kit de Waal