FRun Sample fView Source

Get Paid To Write Online

Get Paid to Write at Home

Get Instant Access


Use Encodings Set Culture and Region Handle Multiple Encodings Display Multiple Currencies

Back to Index

Get URL for this page

How Do I...Display Multiple Currencies (the Euro and local currency)?

This sample illustrates how to use multiple currencies such as the Euro and German DM (Deutsch mark) in your application.

The System.Globalization.NumberFormatInfo class contains formatting information such as the currency symbol, decimal digit, separator, and so on. In many European countries, two separate currencies are commonly used: the Euro and the local currency. A static property NumberFormatInfo.CurrentInfo contains current local currency info, and the Currency symbol that is associated with the Euro. To represent the local currency and the Euro, you must first create a copy of the NumberFormatlnfo instance using NumberFormatInfo.Clone(), then replace the CurrencySymbol property with the local currency symbol.

Dim LocalFormat As NumberFormatlnfo = CType(NumberFormatInfo.CurrentInfo.Clone(), NumberFormatlnfo) LocalFormat.CurrencySymbol = "DM" ' Replace currency symbol with DM symbol.


VB MultiCurrency.aspx [Run Sample] | iView Source]

Input and Output

Read a text file

List a directory

Create a log file

Read and write large files

Read and write binary data

Watch file system changes

Back to Index

Get URL for this page

This sample retrieves information from a text file, and uses an ArrayList to display that information for the user.

Opening and reading files for read access is an important part of IO functionality, even if you do not need to write to the file in question. In this example, we open a file for reading. This is useful for reading text files, but inappropriate for binary files. In this example, we use one of many methods available for opening the file. Although many data structures are available for storing information retrieved from the file, an ArrayList is the easiest to use. A more detailed analysis of the code follows the example.

VB Anagrams.aspx

To open a file, you need to manipulate a number of objects found in the IO namespace. The first class of interest is the File class, which defines the general methods and rules for dealing with files. The File class has a number of different methods for opening files, but for this specific scenario, the most appropriate is OpenText. This is because this particular method returns a StreamReader object, which is ideal for reading lines of information from a standard text file. The following code demonstrates using the OpenText method, passing it the name of the file you intend to open. You can include a fully-qualified path when specifying the file.

Dim din As StreamReader = File.OpenText ("words.txt")

Here are some other ways in which you can open files. Each of these alternative samples could replace the previous sample, although with this code, you have to do a bit more work to translate the return value back to a StreamReader object. This is because each of these methods returns a Stream object, which can be used to construct a new instance of StreamReader. While you can use a Stream to read information from a file, a StreamReader lessens your workload by providing you with a richer set of methods that you can use to get information from the file that you have opened.

' Use OpenRead which opens a file in read-only mode

Dim din As StreamReader = New StreamReader( File.OpenReadCwords.txt") ) ' Use Open, which accepts the FileMode to open the file in.

' Here we request FileMode.Open, but an alternative would have been Create, or OpenOrCreate Dim din As StreamReader = New StreamReader( File.OpenCwords.txt", FileMode.Open) )

Once you have opened your file, you will need to get the information from it. As mentioned earlier, the StreamReader is good for this because it provides you with the ReadLine method which enables you to get one line at a time. Of course, you need to know how the information in your file is stored to interpret it correctly. In this sample, the input file consists of one-word lines of information, making it easier to interpret.

You can place the information you retrieve into a number of datastores. In this example, you could just place each line in a string, but that is not typically what would happen. An array is a possible solution, but there is no way to tell in advance how many lines it is going to read. It would have to keep resizing, or remaking, the array (which would require extra work). The ideal solution in this scenario is to choose an ArrayList, a collection on which we can simply use the Add method to add more elements. This saves a lot of effort.

The following sample reads each new line from our opened file and places each new piece of information into an ArrayList. You can detect the end of the file by checking to see if the last thing that was read was null. If it was, then it has reached the end of the file (note that an empty line will not equal null).

Dim str As String

Dim al As ArrayList = New ArrayList() ' make our temporary storage object

' loop through all the rows, stopping when we reach the end of file Do str = din.ReadLine()

If str <> Nothing Then al.Add(str) ' add each element to our ArrayList

End If

Loop Until str = Nothing

Now that you have all your information from the file, you can manipulate it at will. In this example, you can choose to simply print out the information for the user. To do this, you can use a for each statement to go through all the elements in the ArrayList, printing each item to the Console object.

Dim s As String

For Each s in al

Console.WriteLine (s)

Next s


You can read information from a text file in a number of ways. One of the easiest is to use the File object's OpenText method, in combination with a StreamReader object to to retrieve one line of information at a time. It is recommended that you store the information you are retrieving in a temporary store such as an array, or an ArrayList.

Input and Output

Read a text file

List a directory

Create a log file

Read and write large files

Read and write binary data

Watch file system changes

Back to Index

How Do I...Enumerate directories and their contents?

This sample illustrates how to use the DirectoryInfo class to create a directory listing. This is a great way to quickly list files for users or reports, or to find basic information about a specific directory. When used in combination with FileInfo, you can get all the information you need about files and directories in a specific directory.

Get URL for this page VB Directory.aspx fRun Sample! | fView Source]

The ability to look over files and subdirectories for a given directory is essential for many programming tasks. This QuickStart shows you how to use the FileInfo and DirectoryInfo classes. Why not the File and Directory classes? This QuickStart intends to display information such as the size, and creation date for a given file. In this case, it is easier to use FileInfo and DirectoryInfo objects. The File class focuses on the use of non-instantiated (static in C#, or shared in Visual Basic) methods, while the FileInfo class offers methods based on an instance of a FileInfo object. Directory and DirectoryInfo are similar.

The first task explains how create an instance of the DirectoryInfo object (based on the current directory), then find the fully-qualified path of that directory. Next, you can make a table of all the files and directories inside our current directory, so it will print the full path of the current directory at the top of that table. We use the GetFullPath method of the Path class to determine the fully-qualified path of our directory.

' don't forget your Imports statements at the top of your code... Imports System Imports System.IO

' make an object which represents our current directory. The dot (".") represents this directory Dim dir As DirectoryInfo = new DirectoryInfo(".")

' make the header for our table, letting the user know the path we are in...

Console.WriteLine("Following is a listing for directory: {0}", Path.GetFullPath(dir.ToString()))

The objects inside the directory can be files or directories. You can iterate through the directory twice, looking for files first, and directories next. An alternate solution is to use the FileSystemInfo object, which can represent a FileInfo or a DirectoryInfo object. This means you only have to iterate through the collection once. Then, call the GetFileSystemInfos method of the object created in the code above, which returns an array of FileSystemInfo objects. You can iterate through that array with the foreach (For Each in Visual Basic), as the following code demonstrates.

Dim fsi As FileSystemInfo

' loop through our array of FileSysteminfo objects For Each fsi In dir.GetFileSystemInfos()

' ... the code in the following samples goes here.

Next fsi

So now you can see what kind of object each element of the FileSystemInfo array is, and process it accordingly. First test the instance of the FileSystemObject to see if it is a file. If it is, create a new instance of the FileInfo object to represent it. This enables you to call the methods particular to that kind of object. If you do not do this, you could not call properties such as Length, which does not exist in FileSystemInfo. In contrast, CreationTime is a property of the FileSystemInfo object, which is why you can deal with it before you enter your If statement, regardless of whether you have a file or a directory.

Notice that you are shortening the name you display to the user, primarily to save screen space. Because there can be file access or other related exceptions, execute this code in a Try block, to make sure it does not end abnormally. Put this code together with the code in the previous examples, and you have your program (once inside a method, of course). Note that this only demonstrates how to process a file.

Dim creationTime As DateTime = fsi.CreationTime Dim subLength As Integer = 2 5

If (fsi is FileInfo) Then ' check to see if the current object is a file... Dim f As FileInfo = CType(fsi, FileInfo)

' this if statement simply ensures that we do not shorten the ' name of the file too much! if f.Name.Length < subLength Then subLength = f.Name.Length

End If

Dim name As string = f.Name.Substring(0, subLength) Dim size As long = f.Length

' format the output to the screen

Console.WriteLine("{0, -25} {1,-12:N0} {2, -12} {3,-20:g}", _

name, (size + " KB").PadLeft(12), "File", creationTime)

Else ' it must be a directory End If

Catch ' ignore!!! errors such as 'file being used' and so on...

End Try


You can working with files and directories using FileInfo and DirectoryInfo, although you can also use File and Directory as alternatives. By working with the Info-based objects, you need an instance of the class, but you can easily obtain specific information about a file or directory (such as size, or creation date).

Input and Output

Read a text file

List a directory

Create a log file

Read and write large files

Read and write binary data

Watch file system changes

Back to Index

This sample illustrates how to create a basic log file using the IO classes. This demonstration introduces many useful concepts such as writing to a file, and opening a file, even if the file does not yet exist. Since the information written to the file needs to be shown to the user, this example also demonstrates reading a file.

Get URL for this page VB Logfile.aspx fRun Samplel | fView Sourcel

Reading and writing information to and from a file is a common task, which you will no doubt come across when programming. Many programs regularly deal with reading and writing (Microsoft Excel, Microsoft Word, or Microsoft Powerpoint are a few examples). This example shows how to create log file that is a text file (as opposed to a binary file), so you can open and read the file.

The example shows you how to create a FileStream object. A FileStream holds a reference to a file that you can manipulate. There are a few things that the FileStream needs to be given when making a reference to our file. First, it needs the name of the file. Next, you have to designate to the FileStream the mode in which you want to refer to our file. We could ask it to only open an existing file, but that means if the file does not exist, it will cause a problem. Therefore, we are going to tell the FileStream to open the existing file if it is there, or create a new file if it is not. Finally, you have to designate to the FileStream the kind of access you want to the file (read, or write). This example will demonstrat reading and writing.

' make a new FileStream object, ready for read and write steps.

Dim fs As FileStream = New FileStreamClog.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)

Now that you have a reference to your file, the next step is to write some log information into it. To do this, you need to create a StreamWriter, an object that can write a string into a Stream object. If you are familiar with the FileStream object, you might be wondering why we do not use its Write method. Why make the StreamWriter object at all? Because a FileStream can only write an array of bytes to a file, and many times (as in this example) you might want to write other kinds of data, such as strings. A StreamWriter can write strings to our file, while our FileStream cannot. This is going to make your job a lot easier.

The following segment demonstrates how to create a new StreamWriter. Notice that the StreamWriter is made with a reference to the stream. Having made the stream, you can use the Seek method to get to the end of the file (if you do not do this, and the file already exists, you would be putting your new information in the wrong place), then use the Write method to write your strings into the file. Note that Write itself does not guarantee that the strings get into the file, therefore to force the information through the FileStream, invoke the Flush method on your Writer.

Dim w As StreamWriter = New StreamWriter(fs) ' create a stream writer w.BaseStream.Seek(0, SeekOrigin.End) ' set the file pointer to the end of file w.Write("Log Entry : {0}", vbcrlf)

w.WriteLine("|0j {l}{2}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), vbcrlf) w.WriteLine("--Log Entry goes here--")

w.Flush() ' update underlying file

At this point, you have finished updating your log file. Normally, you would shut the file so anyone can open it and see the log entries. To read the file, you have to make a StreamReader. Again, the FileStream does have a Read method, although creating a StreamReader makes this easier. Having made the StreamReader, you need to point it to some place in your file, although this time you are going to move to the beginning of the file and move from there.

In order to determine when you have reached the end of the file, you have to 'peek' at the file from the current position of the StreamReader current position. If you have reached the end of the file (signified by a value less than zero), it does not keep reading the file since there is no information left. However, if there is still some information to read, you can instruct your reader to get the next line of information, using its ReadLine method. Once finished, you can close the Stream, the Reader, and the Writer.

Dim r As StreamReader = New StreamReader(fs)

r.BaseStream.Seek(0, SeekOrigin.Begin)

output.Append(r.ReadLine()) output.Append( chr(13) ) End While w.Close()

create a Char reader set the file pointer to the beginning while not at the end of the file get the next line of information from the file a newline close the writer and underlying file r.Close() ' close the read

The result is a readable file. This functionality is ideal for server administrators as well as those who maintain websites. You can track performance information, the number of hits for a site, as well as numerous other logging tasks that do not require a database.

Input and Output

Read a text file

List a directory

Create a log file

Read and write large files

Read and write binary data

Watch file system changes

Back to Index

Get URL for this page

How Do I...Read and write large files?

This sample demonstrates how to write a large file and read it back in. This sample also shows how to time such operations. It accepts a file size (measured in kilobytes) from the user, indicating the size of the file to create. The larger the specified size, the longer the process will take to both write and read the temporary file created. When working with large files, it is a good idea to give consideration to mechanisms to divert a user's attention away from the processing, such as progress indicators, or splash screens.

VB LargeReadWrite.aspx fRun Samplel | ["View Sourcel

This sample uses objects found in the IO namespace, but now you will write a large amount to a file. This concept builds on the issues discussed in How Do I...Create a log file?. However, this time you will use Binary readers and writers. This sample will also demonstrate how to measure the length of the process.

The first thing you have to do is determine the size of the file to create. This example asks the user to specify a file size, making sure that they are warned in advance about specifying numbers which are too large. The information comes from the user through a text field on our aspx page. For more details on creating the ASP.NET aspects of our example application, please review the topics listed under Welcome to the ASP.Net QuickStart Tutorial.

Once you have the file size from the user, the next step is to create a file of that size. You could create a file that specifies the size, but you generally do not know in advance how big you are going to make your file (the situation we have here is fictitious, and just for demonstration). Therefore, this example only writes one byte at a time to the file. As you can imagine, this could potentially be a very long process.

There are a few steps required to make the file. First, you need to take the size specifed by the user, and convert it to kilobytes, which is the measurement the example asked the user to specify, so you multiply their number by 1024. Now that you have the correct total, you need to create a reference to the temporary file. This example uses a FileStream object. When you make your reference, you need to specify a file name (make sure it is a test file because you do not want to accidently replace a necessary file), and the FileMode in which to open the file. Since you are not concerned if the file already exists (just in case you forgot to remove it previously), this example specifies how to open the file in OpenOrCreate FileMode. This means that it will open the file if it exists, or create it if it does not. Having made the reference, you can ensure the file is empty by setting the length of the Stream to zero, as in the following sample.

' a variable to hold the size of the file as specified by the user (fileSize) Dim origTestSize As double = fileSize

' a variable to hold the actual size of the file we want to make Dim testSize As double = origTestSize * 1024

Console.WriteLine ("Running test with size {0} KB", origTestSize.ToString()) Console.WriteLine ("This may take a while...")

FileStream fs = new FileStreamCdata.bin", FileMode.OpenOrCreate) fs.SetLength(O)

Now that you have your file ready to populate, you can begin the writing process. In this example, you will make a binary file, so you are going to create a BinaryWriter object. You need to make sure that the writer is pointing to the beginning of our file, so use the Seek method to move to the front of the file, and then loop through the file, writing the specified number of bytes to the writer. The nature of the information does not matter, since the process is important here, so we are just writing a series of ones. Once finished, you force the changes back into the file by flushing the stream. Note that at the point you write the first byte to the file, you get the current TickCount from the Environment you are operating in. You will use this to determine when you began the writing process. You can also take a count once the write is over, to determine the total duration for the write process.

Dim w As BinaryWriter = New BinaryWriter(fs) ' create a BinaryWriter w.BaseStream.Seek(0,SeekOrigin.Begin) ' seek the beginning of the file

Dim beginWrite As Integer = Environment.TickCount ' get the start time

Dim intCount As Integer

For intCount = 0 To testSize - 1 ' loop through the file, writing the bytes w.Write( CType(1, byte)) ' do the write intCount = intCount + 1 Next intCount fs.Flush()

Dim endWrite As Integer = Environment.TickCount ' get the end time ' ... feed the information back to the user ...

Having performed the Write, it is important to let the user know the results, so you will notice that the complete sample feeds back the information to the console. The next important step is to get the information out of the file, to see how long it takes us to read the file. In a fashion similar to writing, create a BinaryReader, once again setting the current postiion to the beginning of the file using the Seek method. Again take a TickCount to determine the start time, and loop through the file, reading each subsequent byte until the end of the file. Once again, flush the information from the Stream, and take a count of the ticks at the end of the process. Once you give the information back to the user, it's important to close the FileStream, and because you are making a demonstration file, use the Delete method of the File class to remove the file.

Dim r As BinaryReader = New BinaryReader(fs)

create a BinaryReader w.BaseStream.Seek(0,SeekOrigin.Begin) ' set the file pointer to the beginning

Dim beginRead As Integer = Environment.TickCount ' get the start time

For intCount = 0 To testSize - 1

dummyInt = r.ReadByte() intCount = intCount + 1 Next intCount fs.Flush()

Dim endRead As Integer = Environment.TickCount ' ... feed the information back to the user ...



loop through, reading the bytes do the read determine the end time close the file delete the file

Creating and reading a large file is not much different from creating files of other types. It is good to be aware of the specific methods and properties associated with different input and output techniques, and the classes available to assist you with your IO tasks, such as Binary Readers and Writers. Make sure that you keep in mind your current position when dealing with large files.

Input and Output

Read a text file

List a directory

Create a log file

Read and write large files

Read and write binary data

Watch file system changes

Back to Index

Get URL for this page

How Do I...Read and write binary data?

This sample illustrates basic binary file input and output using the BinaryReader, BinaryWriter and FileStream classes. A similar topic is presented under the heading How Do I...Create a log file?. Reading and writing binary information enables you to create and use files that are not accessible through other input and output methods. This example also demonstrates writing non-string data, and demonstrates the capabilities of binary I/O.

VB ReadWrite.aspx

Although files on your computer can be stored in different types and files, one of the more common formats for files is a binary format. This short introduction to creating binary files uses the base classes BinaryReader and BinaryWriter to get information from, and put information into a file. Each of these classes wraps a stream of information, so before going further, you need create a stream which you can use to write your information to and from. Because you will be creating files, you will use a FileStream to expose a specific file, which in this case, you can modify if it already exists, or create if it does not exist. Once you have your FileStream, you can use it to construct your BinaryReader and BinaryWriter, as in the following example.

' Make a new FileStream object, exposing our data ' If the file exists, open it, and if it doesn't, Dim fs As FileStream = New FileStream("data.bin",

' create the reader and writer, based on our file Dim w As BinaryWriter = New BinaryWriter(fs) Dim r As BinaryReader = New BinaryReader(fs)

To use the BinaryReader, a number of different Read methods are available to interpret the binary information being read from your chosen stream. This example deals with strings of information, so you will be using the ReadString method, but the BinaryReader exposes other readers such as ReadBoolean, or ReadChar for intepreting other data types. When reading information from your stream, use the PeekChar method to determine when you have reached the end of your stream (in this case, the end of the file). PeekChar returns a negative value when you have reached the end of the stream, as in the following sample.


then Create it. FileMode.OpenOrCreate)


' make an appropriate receptacle for the information being read in... ' a StringBuilder is a good choice

Dim output as StringBuilder = New StringBuilder()

' set the file pointer to the beginning of our file... r.BaseStream.Seek(0, SeekOrigin.Begin)

' continue to perform this loop while not at the end of our file... Do While r.PeekChar() > -1

output.Append( r.ReadString() ) ' use ReadString to read from the file


Once you have read in the information, you can do whatever you need with it. At some point however, you are probably going to want to write information back out to the file, so we are going to need our BinaryWriter. In this example, you are going to append information to the end of the file using the Seek method, so make sure the pointer to your file is at the end of the file before beginning our write. There are a couple of choices when writing information with the BinaryWriter. You can use the Write method to write any standard form of information to the stream your writer wraps, since the Write method has plenty of overloads for all the kinds of information you can write. In this situation, you can also use the WriteString method to write a length-prefixed string to the stream. This example uses the Write method. Note that the Write method does accept a string.

' set the file pointer to the end of our file... w.BaseStream.Seek(0, SeekOrigin.End)

w.Write("Putting a new set of entries into the binary file..." & chr(13)) Dim i As Integer

For i = 0 To 5 Step 1 ' some arbitrary information to write to the file w.Write( i.ToString() )

Next i

Having demonstrated the basics of reading and writing binary information, it is always a good idea to open the file you have created with an an application such as Microsoft Word or notepad, just to see what the file looks like. You will notice that the file is not human-readable, since the information gets transformed by the writing process to a form which is easier for the computer to use.

Input and Output

Read a text file

List a directory

Create a log file

Read and write large files

Read and write binary data

Watch file system changes

How Do I...Watch file system changes?

Use the FileSystemWatcher component to monitor a file system and react when changes to it occur. This makes it possible for you to quickly and easily launch business processes when certain files or directories are created, modified, or deleted. For example, suppose you and a group of coworkers are collaborating on a document that is stored on a shared directory on your server. Using the FileSystemWatcher component, you can easily program your application to watch for changes to the shared directory. When a change is detected, the component can run processing that notifies each of the group members through email.

Back to Index

Get URL for this page

This sample illustrates how to use a FileSystemWatcher to watch for any changes, renaming, creation, and deletion of any files in the specified directory. The application takes the directory that you wish to watch as the only argument.

Try running the sample as follows:

Now, open the c:\ directory and try creating, modifying and deleting a file in the directory. Observe the sample application printing an appropriate message to the console window.

In its simplest form, using a FileSystemWatcher involves:

1. Creating a new instance of the component and specifing the directory to watch:

Dim watcher As FileSystemWatcher = New FileSystemWatcher() watcher.Path= "c:\Foo"

2. Adding event handler[s]:

AddHandler watcher.Changed, AddHandler watcher.Created,

3. Specifying what the application should do when a change occurs:

AdressOf OnChanged AdressOf OnChanged

Public Sub OnChanged(source As Object, e As FileSystemEventArgs)

Console.Write("File: {0} {l}", e.FullPath, e.ChangeType) End Sub

4. Enabling the component:

watcher.EnableRasingEvents = True


VB Watcher.exe

Was this article helpful?

0 0

Post a comment