Chapter 8 Files. File Streams

Size: px
Start display at page:

Download "Chapter 8 Files. File Streams"

Transcription

1 Chapter 8 Files Few programs are written that don t involve some type of file input/output. Way back in the days when the C language became popular a set of library functions were designed that have been supported on every operating system that has a working C compiler. These functions include the familiar fopen, fclose, fread, and fwrite. The underlying functions in the operating system itself vary. For example, the CreateFile function in the Windows operating system is such an example. With the introduction of the C++ standard library we were exposed to new class oriented capabilities. The.NET FCL is no different except that I think you will find these classes much easier to use. File Streams File input/output generally falls into two categories, text and binary. It is not surprising that the.net FCL has classes to handle both categories. The System.IO namespace contains most of the classes of interest to us for file I/O. The FileStream class is the basic class to perform raw byte oriented I/O. It is derived from the abstract class Stream as you can see from the following derivation tree: System.Object System.MarshalByRefObject System.IO.Stream System.IO.FileStream The Stream class is not specifically associated with a file and is used as the base class for other purposes as well as file I/O. A stream is a concept you are probably familiar with. A stream is a sequence of some data type that we read from a source or write to a destination. The constructor for the FileStream class has a plethora of overloads. The easiest to use is the following: public FileStream(string path, FileMode mode); Path is a relative or absolute path to the file. Mode is the mode we wish to open or create the file. The FileMode enumeration shown in Table 8-1 specifies the allowable modes. The difference between Create and CreateNew is that Create throws an exception if the file already exists whereas CreateNew merely truncates the file. If you try to Open a file and it doesn t exist then an exception is also thrown. Truncate throws an exception of the file doesn t exist. By default the file is opened for both reading and writing. This can be changed with the FileAccess enumeration which is passed as an optional parameter to the 1

2 constructor. There are other more advanced options also available such as the ability to control file sharing. Table 8-1 FileMode Enumeration Member Description Append Opens the file if it exists and seeks to the end of the file, or creates a new file. Create Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. CreateNew Specifies that the operating system should create a new file. Open Specifies that the operating system should open an existing file. OpenOrCreate Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. Truncate Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its size is zero bytes. We can read raw bytes from the file with the Read method or the ReadByte method. int ReadByte(); int Read(byte[] array, int offset, int count); ReadByte returns the next byte in the file as an unsigned integer. This means it has a value between 0 and 255 rather than between -128 and In other words the high order bytes of the resulting integer are all zero and the byte value is not sign extended. If the end of file is reached then -1 is returned. Read reads count bytes into array starting at the index specified by offset. The actual number of bytes read is returned by the method. Fewer than count bytes would be read if the end of file was reached. There are two corresponding methods for writing to the file stream: void WriteByte(byte value); void Write(byte[] array, int offset, int count); WriteByte writes a single byte and Write writes count bytes starting at index offset from array. When we are finished performing I/O on a file we should always close the file with a call to the Close method. This releases resources and ensures that all bytes are written to the file in the case where we have written or appended to the file. As you will see in the following example, it is customary to do this in a finally block of an exception handler. A common task is to copy a file independent of its format. The FileStream class is ideal for this purpose. The following example is a bit unrealistic as a useful program. File copy operations are always built into the user interface provided by the operating system vendor. Windows provides convenient file 2

3 copying by dragging and dropping using the Explorer. Copying from a command prompt is equally simple. Nevertheless our program demonstrates the central operations of opening, reading, writing, and closing files. The user interface also demonstrates the use of the common file open and save dialogs I discussed in Chapter <ref>. Figure 8-1 shows the form as displayed by the designer. Everything is straightforward except for the two icons shown below the form. Visual Studio 2005 has some items in the toolbox that don t directly render in the form itself. There is an OpenFileDialog and SaveFileDialog tool. If you drag these tools to the form code is being generated for you. This code allows bringing up the appropriate dialog in response to a program action. Since these tools don't appear on the surface of the form they are shown below. You can click on them and open the properties window just like any other control and set properties without ever typing a line of code. Figure 8-2 shows the properties window for the open file dialog. In this case I only changed the name. Figure 8-1 3

4 Figure 8-2 Each of the "Browse" buttons merely opens the appropriate dialog by calling the ShowDialog method. If the dialog returns DialogResult.OK then the complete file path is copied to the Text property of the appropriate TextBox. A nice feature of the SaveFileDialog is that it checks if the file exists and gives the user the chance to type in another name. Of course you might want to replace the selected file. This behavior can be modified by setting the property OverwritePrompt to false. A similar behavior checks that the file exists in the OpenFileDialog. Another behavior you might notice is that the open and save dialogs have memory. They remember the last folder you visited. You might be tempted to conclude that this behavior is unique to.net. As it turns out it's not..net merely wraps a class around the appropriate Windows common dialog inside the operating system itself. The operating system remembers this information in the registry. Figure 8-3 shows the program code. FileCopy - Form1.cs 4

5 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace FileCopy public partial class FileCopy : Form public FileCopy() InitializeComponent(); private void browsesource_click(object sender, EventArgs e) if(opendlg.showdialog(this)==dialogresult.ok) source.text=opendlg.filename; e) private void browsedestination_click(object sender, EventArgs if (savedlg.showdialog(this) == DialogResult.OK) destination.text = savedlg.filename; private void copy_click(object sender, EventArgs e) FileStream infile=null, outfile=null; byte[] buffer = new byte[512]; int count; if (source.text == "" destination.text == "") MessageBox.Show("Both source and destination files must be specified!"); return; if (source.text == destination.text) MessageBox.Show("Source and destination file can't be the same!"); return; try infile = new FileStream(source.Text, FileMode.Open); outfile = new FileStream(destination.Text, FileMode.Create); while((count=infile.read(buffer, 0, 512))>0) outfile.write(buffer, 0, count); 5

6 catch (Exception ee) MessageBox.Show("Copy failed!\n" + ee.message); finally if(infile!=null) infile.close(); if(outfile!=null) outfile.close(); Figure 8-3 The processing when the copy button is clicked is straightforward. In order to prevent attempting to perform a copy when there is a missing file both file paths are checked to make sure they are not missing. If one or both are then a message box is displayed and the copy operation terminated. We would never want to coy a file over itself and so an additional test is made that compares the two paths to make sure they are different. There is actually a slight deficiency here. It is possible for the user to type in just the file name in the destination text box and if it is the same name as the file in the source then an error would result if the folders for both files were the same. The program won t detect this since it is comparing the full paths as it must. Duplicate file names would be legal if the folders were different. More advanced techniques can be coded to detect this type of error if you wish. However, as you will see shortly we catch this error in another way. The actual file copy is accompliahed by the following lines of code: infile = new FileStream(source.Text, FileMode.Open); outfile = new FileStream(destination.Text, FileMode.Create); while((count=infile.read(buffer, 0, 512))>0) outfile.write(buffer, 0, count); The first two statements open the respective files in the appropriate modes. The copy is buffered by reading up to 512 bytes at a time. We need to make sure the actual count is determined so we don t overwrite the destination file. The resulting file sizes should be exact. Read returns a zero value when the end of the file is reached. These statements are placed inside a try/catch to detect any errors. A possible error might result if the access permissions prevent writing in the directory or the source file doesn't exist. If an exception is generated the program displays a message box with the exception message displayed. Figure 8-4 shows the application with some files entered. Figure 8-5 shows the result of attempting to open a non-existent file. 6

7 Figure 8-4 Figure 8-5 In practice it is usually not a good idea to return raw exceptions to the user. A better approach is to have a catch block for each different exception and provide the user an appropriate message box or take an appropriate action. If we do inadvertently try to copy a file over itself we will get the exception shown in Figure 8-6. This results because the file open operation opens the file for exclusive access and this prevents opening the file for any other operation. Figure 8-6 The finally block contains the following two statements: if(infile!=null) infile.close(); if(outfile!=null) outfile.close(); It is necessary to test to make sure the file was actually opened before attempting to close it. It is also important to note that I explicitly initialized both infile and outfile to null. If you neglect to do this the compiler will give you an error indicating that you have attempted to use an unassigned local variable. This is a 7

8 feature of C# that helps prevent errors that have plagued programmers in the past. Previously compilers and languages made it difficult or impossible to make such a test. Flush and Seek Two methods are also included with the file classes that you should be aware of. When we write a file there is buffering internal to the operating system. This is necessary because we can only write blocks of data to a disk device. This is also true of some other output streams such as a network connection. There are instances when we might want to ensure that all pending output is actually written to the device. This might be important if we are worried about a program crashing for some reason and we want to preserve as much data as we can. The following call does the trick: file.flush(); File is the identifier for the file stream you wish to flush. It is possible to start reading or writing anywhere within a file. The Seek method allows us to set the position for the next read or write to any position we want. The following is the signature for the call: long Seek(long offset, SeekOrigin origin); Offset specifies the offset in bytes from the position specified by the origin argument. Origen is one of the values from the SeekOrigen enumeration shown in Table 8-2. The return value is the new position in the stream. Table 8-2 SeekOrigen Enumeration Member name Description Begin Specifies the beginning of a stream. Current Specifies the current position within a stream. End Specifies the end of a stream. Stream Readers and Writers The FileStream class can be used to read and write virtually any data type if we are willing to convert the data to raw bytes. While there are many instances of binary files that are of interest to the programmer, a far more common requirement is to read and write text files. The StreamReader and StreamWriter classes make working with text files very easy since we can work with characters or character strings rather than raw bytes. I will discuss these classes before moving on to classes that allow reading and writing of binary data. 8

9 Character Sets Unfortunately there is now universal standard for the format of text files. Even if the file is in the ASCII character set there are still issues with the line terminator standard. The standard for Unix/Linux, Windows, and the MAC OS are all different. Many times the differences are not visible to you since clever software can do the appropriate conversion. Examples are downloading files using FTP or rendering a page written in HTML by your browser. HTML is actually written as a text file with markups that are just special sequences of characters. Another difference between text files that is becoming more and more important is the use of non-ascii character sets such as Unicode. C#'s representation of characters and within strings is Unicode. Unicode is a 16-bit character code whereas ASCII is 7-bit or 8-bit if we use an extended version. The 8-bit version of ASCII is formed by adding an additional 128 characters from the ISO Latin Alphabet. Extended ASCII is sometimes referred to as the ANSI character set. The first 256 characters of Unicode correspond to this character set. In other words, if the high order byte is zero then the Unicode character is extended ASCII or ANSI. You can learn all about the Unicode character set at You probably want to read and write ASCII characters to your text file since this is currently the most popular character set across all platforms. Unfortunately the default for the StreamWriter and StreamReader classes is neither Unicode or ASCII. Instead it is UTF-8. UTF stands for Unicode Transformation Format. There are a number of these transformations and you can learn all about them at the URL I mentioned above. Basically, a UTF transforms Unicode characters into alternate representations. In UTF-8 each Unicode character is translated into from one to six bytes. If the character is in the non-extended ASCII character set, in other words less than 128, then this value is stored in a single byte. If you only use ASCII compatible characters in your strings then you get an output file that is ASCII compatible. This is usually what you want. If you want to use the extended ASCII character set you need to specifically construct your stream to use that encoding. There are quite a few constructors for the StreamWriter and StreamReader classes. Here are the three most useful for StreamWriter: StreamWriter(string path); StreamWriter(string path, bool append); StreamWriter(string path, bool append, Encoding encoding); The first opens path for writing in UTF-8 encoding. We can specify that we want to append to an existing file by setting append to true in the second format. The encoding can be controlled with the third form of the constructor. The following constructs a StreamWriter that encodes in ASCII. StreamWriter writer = new StreamWriter(mypath, false, Encoding.ASCII); 9

10 To write to the stream we use one of many overloads to the Write method. We can actually write text versions of most of the basic data types such as an integer. Think of this as using the ToString method of the data type to convert it to a string and then writing the string. To get a better handhold on the capabilities of these methods we need to seek out the base class for StreamWriter. StreamWriter inherits from TextWriter, an abstract class that is used elsewhere in the FCL. TextWriter allows formatting strings the same way as using the Format method of the string class. Here are a couple of examples: writer.write("a simple string."); writer.write("count = 0", count); Line Terminators The standard line terminator for Windows systems is the pair of ASCII characters CR LF. These correspond to 0x0D and 0x0A in hexadecimal. This corresponds to the string "\r\n." The default for the StreamWriter class. We use the WriteLine method to automatically add these terminators to the string we are outputting. WriteLine has the same overloads as Write. The NewLine property can be used to change this string. You might want to do this to write files to a Unix system where the termination string is "\n." Here is an example: writer.writeline("a complete line."); Reading using a StreamReader is straightforward. The easiest method to use is ReadLine. This method returns the next input line as a string. It returns null if the end of file is reached. The line terminator is stripped from the string. Here is a simple loop to read input from a StreamReader and echo it to the console: while ((s=reader.readline())!=null) Console.WriteLine(s); If you want to read the entire file into a string you can do this with the following call: string s = reader.readtoend(); In this case the line terminator is not stripped off. A StreamReader Example The ReadFile example pulls together a number of techniques we have covered in previous chapters as well as using the StreamReader class. Our goal is to provide a simple program to open and read a text file into the client area of a form and display it. A menu is provided with a menu item to open the file. The content of the file is displayed in a scrollable panel. Figure 8-7 shows what our form should look like without any file displayed. These are the steps needed to set up the form using the designer: 10

11 1. Change the form's title. 2. Drag a menu strip to the form. 3. Add a File item and an Open item under the File item. 4. Add an event handler for the Open item. 5. Drag a panel to the form. 6. Set the panel's AutoScroll property to true. 7. Set the panel's Dock property to Fill. 8. Add a Paint event handler for the panel. 9. Drag a FileOpenDIalog to the form. 10. Set the Filter property to "Text Files *.txt All Files *.*". Step 10 sets up the file matching patterns to either *.txt or *.*. It's a good idea to alert the user that it is appropriate to only open files of type text. Allowing all files allows a cautious user to open file of any type, but it is up to them to make sure they are actually text files. You can add as many filters as you want. Each one consists of a pair of values, the description and the pattern to match. The first pattern listed is selected by default when the dialog is opened. Figure 8-7 Now we can take a look at the code in Figure 8-8. The event handler for the Open menu item starts by showing the FileOpenDialog. After the file is opened each line of the file is read into an ArrayList object. These operations are placed in a try/catch as discussed above. The last step is to invalidate the form and its child controls. The Boolean true value passed to Invalidate assures that the panel will be painted immediately. If you don't do this you will find that the panel doesn t display the text until you cause a repaint by resizing the form or restoring it from the task bar. 11

12 Painting the panel is easy except for the management of scrolling. What value do we set for the AutoScrollMinSize property? We want this dimension to be big enough to display all of the text. The height is easy to compute if we know the number of lines and the height of each line. What about the width? If the font used is a proportionally spaced font then it is not as simple as multiplying the maximum number of characters by a fixed character width. Fortunately there is an easy way to do this. The MeasureString method of the Graphics class allows us to determine the exact bounds of a character string in a particular font. These lines of code calculate the maximum width and height required: foreach (string s in lines) extent = g.measurestring(s, Font); maxh += extent.height; maxw = Math.Max(maxw, extent.width); We merely add up all the heights and determine the maximum length line. The program adds a margin of 50 pixels an d offsets the text by 10 pixels right and down. The AutoScrollMinSizeI is set to this value. You should note that the SizeF object must be converted to a Size object. Fortunately there is a method to do this in the SizeF class. A TranslateTransform is used for the scrolling as I discussed in Chapter <ref>. ReadFile - Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO; namespace ReadFile public partial class Form1 : Form public Form1() InitializeComponent(); private void opentoolstripmenuitem_click(object sender, EventArgs e) StreamReader infile = null; string line; if (opendlg.showdialog() == DialogResult.OK) lines = new ArrayList(); 12

13 try infile = new StreamReader(openDlg.FileName); while((line=infile.readline())!=null) lines.add(line); catch MessageBox.Show("Can't open file!"); return; finally if (infile!= null) infile.close(); Invalidate(true); ArrayList lines; private void panel_paint(object sender, PaintEventArgs e) int dy = 0; float maxh = 0, maxw = 0; SizeF extent; Graphics g = e.graphics; if (lines == null) return; //compute size of text foreach (string s in lines) extent = g.measurestring(s, Font); maxh += extent.height; maxw = Math.Max(maxw, extent.width); maxw += 50; maxh += 50; panel.autoscrollminsize = (new SizeF(maxw, maxh)).tosize(); g.translatetransform(panel.autoscrollposition.x, panel.autoscrollposition.y); foreach (string s in lines) g.drawstring(s, Font, Brushes.Black, 10, 10 + dy); dy += Font.Height; Figure 8-8 String Writers The StringWriter class works just like a StreamWriter except that the output goes to a string rather than a file. We can construct a new StringWriter like this: 13

14 StringWriter sw = new StringWriter(); We can then write formatted output using the Write and WriteLine methods. The following lines of code create a formatted string: int count = 1234; sw.writeline("count is equal to 0, count); string s = sw.tostring(); Of course this is a trivial example and in practice we would use the StreamWriter object in lieu of a file when we want a stream of data that is ultimately dealt with as a string. Simple strings are more easily created using the Format method of the String class that I discussed in Chapter <ref>. An alternative is the StringBuilder class that I discuss in Chapter <ref>. Binary Readers and Writers We can read and write binary files using the BinaryReader and BinaryWriter classes. However, you need to understand the basics of the way in which data types are represented in memory. This may be obvious for integers, but is not quite as clear for floating point types. In many cases the representation of binary data is platform dependent. There are many different formats for the representation of floating point data. If you write data designed for one platform and read it on an incompatible hardware or software platform the results will obviously be disastrous. Even integers are problematic if we need to consider the order the bytes are written to the file. The two formats are known as big endian and little endian. The former writes the high order byte first while the latter writes the low order byte first. Intel processors use little endian while Motorola processors use big endian. A thorough discussion of this topic is not essential if you are not interchanging binary data between applications and/or platforms. It is certainly not something that you probably want to hear all about right now. I just want to make you aware of the issue. A simple example of reading and writing a binary file is probably what you are most interested in at this point. The example in Chapter <ref> where we displayed small ellipses in response to mouse clicks will form the basis of our example. Let's use a binary file to store the collection of points such that we can read them back in at a later time. Of course we could also write this information by converting the coordinates to text and using an appropriate separator character between the values. This would not be as compact as a binary file however. Most of the program is straightforward. I have added a menu strip, open file dialog, and a save file dialog. The default file extension has been set up to be ".bin" which doesn't usually conflict with other files. You can change it to whatever is desired. I won't go over the details of the mouse click processing as it hasn't been changed. Here is the code necessary to write the collection of point to the binary file: 14

15 FileStream stream = new FileStream(saveFileDialog1.FileName, FileMode.Create); BinaryWriter writer = new BinaryWriter(stream); //Write magic number writer.write(magic); //write the point collection foreach (Point p in coordinates) writer.write(p.x); writer.write(p.y); writer.close(); The first step is to create a FileStream associated with the file to be written. This stream is then used to construct the BinaryWriter. I then write an integer magic number. This is a common technique to provide some measure of protection from attempting to open a file which is not in the correct format. The likelihood of a file having the same four bytes at the beginning is small. This number will be read in when a file is opened and checked to make sure it is correct. If it is not the same then the user is alerted that the file is not valid. Writing the points out involves writing the two integer values for each point. The final step is to close the BinaryWriter which also closes the stream. The Write method of the BinaryWriter class is overloaded so that there is no need to call a method specifically associated with the data type. Unfortunately it's not possible to use overloading to read binary data. We need to specifiy a method for the specific data type we expect to be reading. Here is the code excerpt needed to read in the binary data and filling the array of points: FileStream stream = new FileStream(openFileDialog1.FileName, FileMode.Open); BinaryReader reader = new BinaryReader(stream); //check for magic number try int i = reader.readint32(); if (i!= magic) throw (new Exception()); catch MessageBox.Show("Not the correct file format!"); reader.close(); return; coordinates.clear(); int x, y; bool done = false; while (!done) try 15

16 x = reader.readint32(); y = reader.readint32(); Point p = new Point(x, y); coordinates.add(p); catch done = true; reader.close(); Invaidate(); Opening the file for reading is similar to creating the file for writing. We also need a FileStream object. When we read a binary file the method of determining when we reach the end of file is handled differently than it is with text files. We use an exception for this purpose. If the file is zero length then an exception will immediately be thrown before we have had a chance to compare the magic number. As you can see, the first read is to the method ReadInt32. Remember that we need to specify the data type we are reading. To make the code more efficient I throw an exception if the magic number doesn't match. If that were not donw then the code necessary to display the message box would have to be duplicated. The remainder of the read operation is a simple matter of reading the file until the exception is generated indicating we have run out of values. Sometimes using an exception as a means to exit a loop is not obvious. In this case I set a boolean flag that causes the while loop to terminate. I could also use a break statement in the catch and set up the while loop to be an infinite loop with while(true)... I personally don't like this construct. Using a boolean flag makes the code clearer to me. The final steps are to close the reader and invalidate the client area to allow a redraw with the new set pf points. The complete program is shown in Figure 8-9 and Figure 8-10 shows the menu options and a few points diaplayed. BinaryFile1 - Form1.cs using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace BinaryFile1 public partial class Form1 : Form private ArrayList coordinates = new ArrayList(); 16

17 private const int magic = ; //the magic number public Form1() InitializeComponent(); protected override void OnPaint(PaintEventArgs e) const int WIDTH = 20; const int HEIGHT = 20; Graphics g = e.graphics; foreach (Point p in this.coordinates) g.fillellipse(brushes.black, p.x - WIDTH / 2, p.y - WIDTH / 2, WIDTH, HEIGHT); protected override void OnMouseClick(MouseEventArgs e) if (e.button == MouseButtons.Left) Point p = new Point(e.X, e.y); this.coordinates.add(p); this.invalidate(); if (e.button == MouseButtons.Right) this.coordinates.clear(); this.invalidate(); private void opentoolstripmenuitem_click(object sender, EventArgs e) if (openfiledialog1.showdialog(this) == DialogResult.OK) FileStream stream = new FileStream(openFileDialog1.FileName, FileMode.Open); BinaryReader reader = new BinaryReader(stream); //check for magic number try int i = reader.readint32(); if (i!= magic) throw (new Exception()); catch MessageBox.Show("Not the correct file format!"); reader.close(); return; 17

18 coordinates.clear(); int x, y; bool done = false; while (!done) try x = reader.readint32(); y = reader.readint32(); Point p = new Point(x, y); coordinates.add(p); catch done = true; reader.close(); Invalidate(); private void savetoolstripmenuitem_click(object sender, EventArgs e) if (savefiledialog1.showdialog(this) == DialogResult.OK) FileStream stream = new FileStream(saveFileDialog1.FileName, FileMode.Create); BinaryWriter writer = new BinaryWriter(stream); //Write magic number writer.write(magic); //write the point collection foreach (Point p in coordinates) writer.write(p.x); writer.write(p.y); writer.close(); private void cleartoolstripmenuitem_click(object sender, EventArgs e) coordinates.clear(); Invalidate(); Figure

19 Figure 8-10 Figure 8-11 shows the contents of a binary file with only one point saved. As you can easily see the file is exactly 12 bytes long. This corresponds to the magic number and the two integer values for the point. Each integer value requires three four bytes. I used The hexadecimal file display feature of Visual Studio 2005 to examine the file. Figure 8-11 Working with Files We have seen how to read and write both text and binary files. However, there are other operations that we are often called upon to perform. Among these are: Delete a file Rename a file Move/copy a file Determine a file's attributes Change a files attributes 19

20 Two classes provide a whole host of operations on files, File and FileInfo. These classes are very similar and in fact duplicate each other for the most part. The primary difference is that File is a collection of static methods whereas FileInfo requires an instance of the class constructed for a particular file. File is a sealed abstract class. Thjis means that we can't instantiate it or derive from it. This is common practice when we wish the class to be used strictly for its static methods. The File Class File has several shortcut methods to create and open both FileStream and StreamReader classes. These include those shown in Table 8-3 File Methods: Table 8-3 File Methods Method AppendText CreateText Open OpenRead OpenText OpenWrite Description Creates a StreamWriter in append mode. Creates a StreamWriter. Opens a FileStream. Opens an existing file for reading using a FileStream. Opens a text file for reading using a StreamReader. Opens an existing file for writing using a FIleStream. Using these static methods rather than the constructors for the respective classes is up to you. Once again this is just an example of the diversity of the.net FCL where there are often several ways to perform the same task. Of more interest are the methods shown in Table 8-4 File Mehods. Table 8-4 File Mehods (sample) Method Description Copy Copies a file. Delete Deletes a file. Exists Tests if a file exists. Move Move a file (does not overwrite.) Replace Replaces an existing file, deletes the original file, and makes a backup of the replaced file. These methods are very simple to use. For example, to copy file1 to file2 the following line of code does the trick: File.Move("file1", "file2"); If file2 exists and exception will be generated. A better method is to test for this condition as well as testing of the source file exists. This is the way to do it: if(!file.exists(file1)) MessageBox.Show("Source file does not exist!"); 20

21 else if(file.exists(file2) MessageBox.Show("Destination file already exists!"); else File.Move("file1", "file2"); Of course you could prompt the user to allow the copy if the file exists and delete the existing file prior to the copy. I have only touched on a fraction of the methods available in the File class, but these are the ones you will most likely want to use to get started. Things like checking attributes on files are not difficult and a quick read of the documentation will reveal the power of the File class. The FileInfo Class There are fewer methods in the FileInfo class and not all of the capabilities of the File class are available. The first thing to do is to construct an instance of the FileInfo class passing the path to the file in the constructor: FileInfo fi = new FileInfo("file1"); We could then copy this file: fi.copyto("file2"); File2 must not exist or an exception will be thrown. This overloaded version allows overwriting: fi.copyto("file2", true); Table 8-5 shows some of the other methods available. You should probably use the FileInfo class when you want to perform several operations on the same file. Table 8-5 FileInfo Methods (Sample) Method Description AppendText Open a text file for appending. Create Create a FileStream. CreateText Create a text file. Delete Delete a file. MoveTo Move a file. Open Open a FileStream. OpenRead Open an existing file as a FileStream for reading. OpenText Open a text file. OpenWrite Creates a write only FileStream. Replace Replaces a file. 21

22 FileInfo has a number properties that represent the properties of the associated file. Table 8-6 shows some of these. Table 8-6 FileInfo Properties (Sample) FileInfo Properties Description CreationTime The file's creation time. Exists True if file exists. FullName The full path name of the file. Extension The file's extension. IsReadOnly True if the file is read only. LastAccessTime The last access time. Length The files length in bytes. Name The file's name. The following lines of code creates a string with the file's creation time in the format normally displayed for file times: FileInfo fi = new FileInfo(filePath); string creationtime = fi.creationtime.tofiletime(); Working with Directories (Folders) In the early days of computing, when file systems were first invented, the data structure used to catalog the files was known as a volume table of contents. At some point, especially after the introduction of hierarchical files systems, the term directory became the standard term. In recent years this term has been replaced by folder. But the term folder has been more widely adopted by users rather than by programmers or within operating system jargon. The classes an documentation for the.net Framework refers to directories more often than folders. I will use the term directory in the discussion to follow. It is interesting to note that all modern operating systems implement directories as a special type of file. In a manner similar to the File and FileInfo classes the.net FCL contains a pair of classes, Directory and DirectoryInfo, that work with directories rather than files. While a directory and a file share many properties, such as a name and access rights, there is a major difference. Directories can be organized in a hierarchical order, whereas a file is a means to store data. While a file may have an internal structure that is germane to a particular application, the operating system regards a file as a single entity. Since directories have a hierarchical structure we need methods to navigate within the hierarchy. The Directory Class 22

23 Just like the File class, Directory is an abstract class. We can't instantiate the class. It is also sealed so that we can't inherit from Directory either. All the useful methods are static. Table 8-7 shows the most common methods for this class. Table 8-7 Directory Methods (Sample) Method Description CreateDirectory Creates a directory including all the directories in the path. Delete Deletes a specified directory. Exists Determines is a directory exists. GetCurrentDirectory Gets the current working directory of the application. GetDirectories Gets the names of subdirectories in a specified directory. GetDirectoryRoot Return volume and/or root information for a path. GetFiles Returns the files in the specified directory. GetLogicalDrives Gets the logical drives on the computer in the form <driveletter>:\. GetParent Gets the parent directory of the specified directory. Move Moves a file or directory to a new location. SetCurrentDirectory Changes the current working directory to the path specified. Generally the directory path can be absolute or relative. If it is relative it is relative to the current working directory. There are numerous other methods that can manipulate the attributes of a directory such as access rights. Since these operations are not as common I won't discuss the details here. Creating a directory is very simple. This line of code will create a directory named sub1 in the root directory of the current drive: Directory.CreateDirectory(@"\sub1"); Note the use of character prefixing the string. This eliminates the need to escape the backslashes. If the directory already exists but is no empty this method will throw an exception. If the directory can't be created because of an access right then an exception will also be thrown. Deleting, moving, and testing for the existence of a directory are equally as easy to use. What's much more interesting is how to obtain the files in a directory and to navigate the hierarchy. We can get all the files in a directory with this line: string[] files = Directory.GetFiles(path); This code snippet would output all the files in the Windows system directory to the console: 23

24 string[] files = Directory.GetFiles(@"\windows"); foreach (string s in files) Console.WriteLine(s); In a similar manner we can get all the directories in the Windows system directory with: string[] dirs = Directory.GetDirectories(@"\windows"); foreach (string s in dirs) Console.WriteLine(s); You can filter the names of the directories or files returned by Directory.GetFiles or Directory.GetDirectories methods with an optional argument with a simple wildcard pattern match. For example, the following returns only text files: string[] files Directory.GetFiles(path, "*.txt"); The DirectoryInfo Class Table 8-8 shows many of the methods of the DirectoryInfo class. The path is provided to the constructor and then we call the appropriate method. Table 8-8 DirectoryInfo Methods (Sample) Method Description Create Creates a directory. CreateSubdirectory Creates a subdirectory Delete Deletes the directory. GetDirectories Gets the subdirectorties of the associated directory. GetFiles Gets the files in the directory. MoveTo Moves a directory. The Path Class Before we develop a more complex example using the Directory and File classes, there is one more class of interest, the Path class. The Path class allows us to parse a path into its component pieces. Table 8-9 lists the most popular methods. All of these methods are static since Path is sealed and abstract. Table 8-9 Path Methods (Sample) Method ChangeExtension GetDirectoryName GetExtension GetFileName Description Change a file's extension. Get the directory name part of a path. Gets the file extension is it exists. Gets the file name part of a path including 24

25 GetFileNameWithoutExtension GetFullPath GetPathRoot the extension. As above but strips the extension. Gets the absolute path for a file. Gets the root of a path. A very common task is to strip the file name from a compete path. This does the trick string filename = Path.GetFileName(@"\c:\dir\subdir\myFile.txt"); and returns "myfile.txt." The TreeView Control This is a perfect opportunity to discuss the use of a very versatile control, the TreeView control. This is a control whose functionality is familiar to most computer users. The Windows Explorer program uses a tree view if the folders view option is selected. The tree view allows an easy display of hierarchical data by the use of nodes that can be expanded or collapsed. This is ideal for directory information. The.NET TreeView control is actually very easy to use and at the same time provides a great deal of functionality. We can set up a TreeView control that uses static data by use of the designer. This might be useful for providing a control to select an item from a predetermined object hierarchy. There is a simple node editor that allows us to set up the nodes in advance of the program's execution. Each node has an associated character string. Expansion and collapsing of the tree is automatically handled by the TreeView control. The Nodes property is a reference to a TreeNodeCollection which in turn contains a collection of TreeNode objects. Figure 8-12 shows the TreeNode Editor at work. I have added a number of nodes. The Text property of each TreeNode is set to whatever you want displayed. 25

26 Figure 8-12 Figure 8-13 shows a program to exercise this TreeView control. The tree view's AfterSelect event handler has been added as well as a simple text box, selection. After you click on a node this event is triggered. You can retrieve the node's text to determine which node has been selected or access the entire hierarchy. Each TreeNode has a Parent property that can be used to navigate to the parent node. The Nodes property references a collection of the nodes child node is any exists. The TreeNodeCollection Count property can be used to determine if any child nodes exist. In this example I merely display the text in the text box. Figure 8-14 shows the result of selecting the "Green" node. TreeView1 - Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace TreeView1 public partial class Form1 : Form public Form1() 26

27 InitializeComponent(); private void treeview1_afterselect(object sender, TreeViewEventArgs e) selection.text = e.node.text; Figure 8-13 Figure 8-14 A Directory Tree What is more interesting is to initialize the nodes of the tree at execution time. This, of course, would be an imperative for a directory browser. As you will see in the following example it requires only a few lines of code to accomplish this task. The major problem to be solved is the fact that we want each node displayed to indicate if it is expandable. The only way to do this is to populate the Nodes collection for that node. That's the way the TreeView control knows to display the + sign or not. For each node we expand we need to obtain the directories contained in that directory as well as the directories contained in each of these subdirectories. Most programmers have been introduced to the concept of recursive programming, but many never learn to utilize the power of this technique. The heart of this example is a method that calls itself to obtain the directories and those directories subdirectories. We could actually obtain the 27

28 entire directory tree this way, but performance would be deplorable. Here is the implementation of this method: private void AddDirs(TreeNode node, bool recurse) node.nodes.clear(); try string[] dirs = Directory.GetDirectories(node.FullPath); foreach (string dir in dirs) if(recurse) AddDirs(node.Nodes.Add(Path.GetFileName(dir)),false); else node.nodes.add(path.getfilename(dir)); catch return; AddDirs is called with a TreeNode object and a boolean flag to determine if the method recurses. The GetDiretories method call is placed in a try block because it is possible that an exception will be thrown if, for example, the user running the program does not have access to the particular directory. In this case we merely ignore the directory. GetDirectories needs to be called with the full path name or it would be relative to the current working directory which would lead to unpredictable results. If recurse is true we add a node to the Nodes collection and pass the new node to another call to AddDirs. This time we make sure that we do not recurse. If we are not making a recursive call then we just add the file name. If AddDirs is initially called with recurse set to true then two levels of the directory hierarchy is added to the directory tree. Remember, we need to go one extra level to make sure the nodes are marked as expandable if they are. The call to the Clear method is required to prevent the repetitive duplication of the same nodes in the collection if we expand a node more than once. The complete program is shown in Figure A text box, path is provided to enter the root directory for the tree. The button named display is used to initialize the tree after we enter a new starting path. The Click event handler creates the root node and then calls AddDirs recursively. This adds the directories contained in the root directory. The BeginUpdate and EndUpdate methods of the TreeView control are used to suppress repainting of the control during the update. It's a good idea to make these calls to improve performance and eliminate flicker. The BeforeExpand event handler of the TreeView is used to populate the node to be expanded. We obtain the node that was selected for expansion from EventArgs and pass it to AddDirs. That all there is to it. DirectoryTree1 - Form1.cs 28

29 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace DirectoryTree1 public partial class Form1 : Form public Form1() InitializeComponent(); private void display_click(object sender, EventArgs e) tree.nodes.clear(); try tree.beginupdate(); tree.nodes.add(path.text); AddDirs(tree.Nodes[0], true); tree.endupdate(); catch return; private void tree_beforeexpand(object sender, TreeViewCancelEventArgs e) tree.beginupdate(); AddDirs(e.Node, true); tree.endupdate(); private void AddDirs(TreeNode node, bool recurse) node.nodes.clear(); try string[] dirs = Directory.GetDirectories(node.FullPath); foreach (string dir in dirs) if(recurse) AddDirs(node.Nodes.Add(Path.GetFileName(dir)),false); else node.nodes.add(path.getfilename(dir)); 29

30 Figure 8-15 catch return; What if we were to change the recursive call to AddDirs within AddDirs to a recursive call? The program would still work, but be extremely slow for large hierarchies. This is a result of the fact that we are not recursing just two levels, but rather the entire directory tree. This obviously is not desirable. Figure 8-16 shows the output with \windows\mail used as the root directory for the tree and the Tours subdirectory expanded. Figure 8-16 I will improve on this program to add the ability to display the files in a directory when I introduce the SplitContainer control in Chapter <ref>. 30

Chapter 6 Dialogs. Creating a Dialog Style Form

Chapter 6 Dialogs. Creating a Dialog Style Form Chapter 6 Dialogs We all know the importance of dialogs in Windows applications. Dialogs using the.net FCL are very easy to implement if you already know how to use basic controls on forms. A dialog is

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Files. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Files. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies 12 Working with Files C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies Chapter Objectives Learn about the System.IO namespace

More information

To start we will be using visual studio Start a new C# windows form application project and name it motivational quotes viewer

To start we will be using visual studio Start a new C# windows form application project and name it motivational quotes viewer C# Tutorial Create a Motivational Quotes Viewer Application in Visual Studio In this tutorial we will create a fun little application for Microsoft Windows using Visual Studio. You can use any version

More information

Windows File I/O. Files. Collections of related data stored on external storage media and assigned names so that they can be accessed later

Windows File I/O. Files. Collections of related data stored on external storage media and assigned names so that they can be accessed later Windows File I/O Files Collections of related data stored on external storage media and assigned names so that they can be accessed later Entire collection is a file A file is made up of records One record

More information

You can call the project anything you like I will be calling this one project slide show.

You can call the project anything you like I will be calling this one project slide show. C# Tutorial Load all images from a folder Slide Show In this tutorial we will see how to create a C# slide show where you load everything from a single folder and view them through a timer. This exercise

More information

Chapter 12. Tool Strips, Status Strips, and Splitters

Chapter 12. Tool Strips, Status Strips, and Splitters Chapter 12 Tool Strips, Status Strips, and Splitters Tool Strips Usually called tool bars. The new ToolStrip class replaces the older ToolBar class of.net 1.1. Create easily customized, commonly employed

More information

File Handling Programming 1 C# Programming. Rob Miles

File Handling Programming 1 C# Programming. Rob Miles 08101 Programming 1 C# Programming Rob Miles Files At the moment when our program stops all the data in it is destroyed We need a way of persisting data from our programs The way to do this is to use files

More information

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

CISC 323 (Week 9) Design of a Weather Program & Java File I/O CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming

More information

In-Class Worksheet #4

In-Class Worksheet #4 CSE 459.24 Programming in C# Richard Kidwell In-Class Worksheet #4 Creating a Windows Forms application with Data Binding You should have Visual Studio 2008 open. 1. Create a new Project either from the

More information

Function. Description

Function. Description Function Check In Get / Checkout Description Checking in a file uploads the file from the user s hard drive into the vault and creates a new file version with any changes to the file that have been saved.

More information

C# Data Manipulation

C# Data Manipulation C# Data Manipulation Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC

More information

C# Data Manipulation

C# Data Manipulation C# Data Manipulation Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC

More information

Create your own Meme Maker in C#

Create your own Meme Maker in C# Create your own Meme Maker in C# This tutorial will show how to create a meme maker in visual studio 2010 using C#. Now we are using Visual Studio 2010 version you can use any and still get the same result.

More information

// Precondition: None // Postcondition: The address' name has been set to the // specified value set;

// Precondition: None // Postcondition: The address' name has been set to the // specified value set; // File: Address.cs // This classes stores a typical US address consisting of name, // two address lines, city, state, and 5 digit zip code. using System; using System.Collections.Generic; using System.Linq;

More information

Files and Streams. Today you will learn. Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads

Files and Streams. Today you will learn. Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads Files and Streams Today you will learn Files and Web Applications File System Information Reading and Writing with Streams Allowing File Uploads CSE 409 Advanced Internet Technology Files and Web Applications

More information

Developing for Mobile Devices Lab (Part 1 of 2)

Developing for Mobile Devices Lab (Part 1 of 2) Developing for Mobile Devices Lab (Part 1 of 2) Overview Through these two lab sessions you will learn how to create mobile applications for Windows Mobile phones and PDAs. As developing for Windows Mobile

More information

F# - BASIC I/O. Core.Printf Module. Format Specifications. Basic Input Output includes

F# - BASIC I/O. Core.Printf Module. Format Specifications. Basic Input Output includes F# - BASIC I/O http://www.tutorialspoint.com/fsharp/fsharp_basic_io.htm Copyright tutorialspoint.com Basic Input Output includes Reading from and writing into console. Reading from and writing into file.

More information

05/31/2009. Data Files

05/31/2009. Data Files Data Files Store and retrieve data in files using streams Save the values from a list box and reload for the next program run Check for the end of file Test whether a file exists Display the standard Open

More information

10Tec igrid for.net 6.0 What's New in the Release

10Tec igrid for.net 6.0 What's New in the Release What s New in igrid.net 6.0-1- 2018-Feb-15 10Tec igrid for.net 6.0 What's New in the Release Tags used to classify changes: [New] a totally new feature; [Change] a change in a member functionality or interactive

More information

IBSDK Quick Start Tutorial for C# 2010

IBSDK Quick Start Tutorial for C# 2010 IB-SDK-00003 Ver. 3.0.0 2012-04-04 IBSDK Quick Start Tutorial for C# 2010 Copyright @2012, lntegrated Biometrics LLC. All Rights Reserved 1 QuickStart Project C# 2010 Example Follow these steps to setup

More information

The Network. Multithreading. This tutorial can be found on -

The Network. Multithreading. This tutorial can be found on - This tutorial can be found on - http://www.informit.com/articles/article.aspx?p=25462&seqnum=5 Instant messaging is sweeping the world, and is rapidly replacing email as the preferred electronic communications

More information

CHAPTER 1: INTRODUCTION TO THE IDE 3

CHAPTER 1: INTRODUCTION TO THE IDE 3 INTRODUCTION xxvii PART I: IDE CHAPTER 1: INTRODUCTION TO THE IDE 3 Introducing the IDE 3 Different IDE Appearances 4 IDE Configurations 5 Projects and Solutions 6 Starting the IDE 6 Creating a Project

More information

Skinning Manual v1.0. Skinning Example

Skinning Manual v1.0. Skinning Example Skinning Manual v1.0 Introduction Centroid Skinning, available in CNC11 v3.15 r24+ for Mill and Lathe, allows developers to create their own front-end or skin for their application. Skinning allows developers

More information

C# 2008 and.net Programming for Electronic Engineers - Elektor - ISBN

C# 2008 and.net Programming for Electronic Engineers - Elektor - ISBN Contents Contents 5 About the Author 12 Introduction 13 Conventions used in this book 14 1 The Visual Studio C# Environment 15 1.1 Introduction 15 1.2 Obtaining the C# software 15 1.3 The Visual Studio

More information

A Summoner's Tale MonoGame Tutorial Series. Chapter 15. Saving Game State

A Summoner's Tale MonoGame Tutorial Series. Chapter 15. Saving Game State A Summoner's Tale MonoGame Tutorial Series Chapter 15 Saving Game State This tutorial series is about creating a Pokemon style game with the MonoGame Framework called A Summoner's Tale. The tutorials will

More information

Basic File Handling and I/O

Basic File Handling and I/O Lecture #11 Introduction File and Stream I/O The System::IO namespace Basic File Handling and I/O The term basic file handling and I/O in Visual C++ refers to various file operations including read from

More information

CHAPTER 2. Troubleshooting CGI Scripts

CHAPTER 2. Troubleshooting CGI Scripts CHAPTER 2 Troubleshooting CGI Scripts OVERVIEW Web servers and their CGI environment can be set up in a variety of ways. Chapter 1 covered the basics of the installation and configuration of scripts. However,

More information

Representing Recursive Relationships Using REP++ TreeView

Representing Recursive Relationships Using REP++ TreeView Representing Recursive Relationships Using REP++ TreeView Author(s): R&D Department Publication date: May 4, 2006 Revision date: May 2010 2010 Consyst SQL Inc. All rights reserved. Representing Recursive

More information

Form Properties Window

Form Properties Window C# Tutorial Create a Save The Eggs Item Drop Game in Visual Studio Start Visual Studio, Start a new project. Under the C# language, choose Windows Form Application. Name the project savetheeggs and click

More information

Chapter 11. Data Files The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 11. Data Files The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 11 Data Files McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter Objectives Store and retrieve data in files using streams Save the values from a list box and reload

More information

XNA 4.0 RPG Tutorials. Part 24. Level Editor Continued

XNA 4.0 RPG Tutorials. Part 24. Level Editor Continued XNA 4.0 RPG Tutorials Part 24 Level Editor Continued I'm writing these tutorials for the new XNA 4.0 framework. The tutorials will make more sense if they are read in order. You can find the list of tutorials

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 11 I/O File Input and Output Reentering data all the time could get tedious for the user. The data can be saved to

More information

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O Introduction The WRITE and READ ADT Operations Case Studies: Arrays Strings Binary Trees Binary Search Trees Unordered Search Trees Page 1 Introduction

More information

C# Continued. Learning Objectives:

C# Continued. Learning Objectives: Learning Objectives: C# Continued Open File Dialog and Save File Dialog File Input/Output Importing Pictures from Files and saving Bitmaps Reading and Writing Text Files Try and Catch Working with Strings

More information

Web Server Project. Tom Kelliher, CS points, due May 4, 2011

Web Server Project. Tom Kelliher, CS points, due May 4, 2011 Web Server Project Tom Kelliher, CS 325 100 points, due May 4, 2011 Introduction (From Kurose & Ross, 4th ed.) In this project you will develop a Web server in two steps. In the end, you will have built

More information

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime Intro C# Intro C# 1 Microsoft's.NET platform and Framework.NET Enterprise Servers Visual Studio.NET.NET Framework.NET Building Block Services Operating system on servers, desktop, and devices Web Services

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Microsoft Windows SharePoint Services

Microsoft Windows SharePoint Services Microsoft Windows SharePoint Services SITE ADMIN USER TRAINING 1 Introduction What is Microsoft Windows SharePoint Services? Windows SharePoint Services (referred to generically as SharePoint) is a tool

More information

CALCULATOR APPLICATION

CALCULATOR APPLICATION CALCULATOR APPLICATION Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;

More information

Eyes of the Dragon - XNA Part 37 Map Editor Revisited

Eyes of the Dragon - XNA Part 37 Map Editor Revisited Eyes of the Dragon - XNA Part 37 Map Editor Revisited I'm writing these tutorials for the XNA 4.0 framework. Even though Microsoft has ended support for XNA it still runs on all supported operating systems

More information

Using Visual Studio. Solutions and Projects

Using Visual Studio. Solutions and Projects Using Visual Studio Solutions and Projects A "solution" contains one or several related "projects". Formerly, the word workspace was used instead of solution, and it was a more descriptive word. For example,

More information

JUnit Test Patterns in Rational XDE

JUnit Test Patterns in Rational XDE Copyright Rational Software 2002 http://www.therationaledge.com/content/oct_02/t_junittestpatternsxde_fh.jsp JUnit Test Patterns in Rational XDE by Frank Hagenson Independent Consultant Northern Ireland

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Part I. Integrated Development Environment. Chapter 2: The Solution Explorer, Toolbox, and Properties. Chapter 3: Options and Customizations

Part I. Integrated Development Environment. Chapter 2: The Solution Explorer, Toolbox, and Properties. Chapter 3: Options and Customizations Part I Integrated Development Environment Chapter 1: A Quick Tour Chapter 2: The Solution Explorer, Toolbox, and Properties Chapter 3: Options and Customizations Chapter 4: Workspace Control Chapter 5:

More information

Programming with Microsoft Visual Basic.NET. Array. What have we learnt in last lesson? What is Array?

Programming with Microsoft Visual Basic.NET. Array. What have we learnt in last lesson? What is Array? What have we learnt in last lesson? Programming with Microsoft Visual Basic.NET Using Toolbar in Windows Form. Using Tab Control to separate information into different tab page Storage hierarchy information

More information

Silverlight memory board ( Part 2 )

Silverlight memory board ( Part 2 ) Silverlight memory board ( Part 2 ) In the first part this tutorial we created a new Silverlight project and designed the user interface. In this part, we will add some code to the project to make the

More information

FILE SYSTEMS. CS124 Operating Systems Winter , Lecture 23

FILE SYSTEMS. CS124 Operating Systems Winter , Lecture 23 FILE SYSTEMS CS124 Operating Systems Winter 2015-2016, Lecture 23 2 Persistent Storage All programs require some form of persistent storage that lasts beyond the lifetime of an individual process Most

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

HOUR 4 Understanding Events

HOUR 4 Understanding Events HOUR 4 Understanding Events It s fairly easy to produce an attractive interface for an application using Visual Basic.NET s integrated design tools. You can create beautiful forms that have buttons to

More information

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

INFORMATICS LABORATORY WORK #2

INFORMATICS LABORATORY WORK #2 KHARKIV NATIONAL UNIVERSITY OF RADIO ELECTRONICS INFORMATICS LABORATORY WORK #2 SIMPLE C# PROGRAMS Associate Professor A.S. Eremenko, Associate Professor A.V. Persikov 2 Simple C# programs Objective: writing

More information

Microsoft Expression Web Quickstart Guide

Microsoft Expression Web Quickstart Guide Microsoft Expression Web Quickstart Guide MS-Expression Web Quickstart Guide Page 1 of 24 Expression Web Quickstart Guide (20-Minute Training) Welcome to Expression Web. When you first launch the program,

More information

PilotEdit User Manual. Author: Date: Version:

PilotEdit User Manual. Author: Date: Version: PilotEdit User Manual Author: support@pilotedit.com Date: 2018-02-28 Version: 11.3.0 URL: http://www.pilotedit.com Table of Contents 1. Introduction... 6 1.1. What is PilotEdit?... 6 1.2. PilotEdit GUI...

More information

Operating System Interaction via bash

Operating System Interaction via bash Operating System Interaction via bash bash, or the Bourne-Again Shell, is a popular operating system shell that is used by many platforms bash uses the command line interaction style generally accepted

More information

Advanced Programming Methods. Lecture 9 - Generics, Collections and IO operations in C#

Advanced Programming Methods. Lecture 9 - Generics, Collections and IO operations in C# Advanced Programming Methods Lecture 9 - Generics, Collections and IO operations in C# Content Language C#: 1. Generics 2. Collections 3. IO operations C# GENERICS C# s genericity mechanism, available

More information

Project 3: Base64 Content-Transfer-Encoding

Project 3: Base64 Content-Transfer-Encoding CMSC 313, Computer Organization & Assembly Language Programming Section 0101 Fall 2001 Project 3: Base64 Content-Transfer-Encoding Due: Tuesday November 13, 2001 Objective The objectives of this programming

More information

Using Dreamweaver CC. Logo. 4 Creating a Template. Page Heading. Page content in this area. About Us Gallery Ordering Contact Us Links

Using Dreamweaver CC. Logo. 4 Creating a Template. Page Heading. Page content in this area. About Us Gallery Ordering Contact Us Links Using Dreamweaver CC 4 Creating a Template Now that the main page of our website is complete, we need to create the rest of the pages. Each of them will have a layout that follows the plan shown below.

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

A Quick Introduction to the Genesis Framework for WordPress. How to Install the Genesis Framework (and a Child Theme)

A Quick Introduction to the Genesis Framework for WordPress. How to Install the Genesis Framework (and a Child Theme) Table of Contents A Quick Introduction to the Genesis Framework for WordPress Introduction to the Genesis Framework... 5 1.1 What's a Framework?... 5 1.2 What's a Child Theme?... 5 1.3 Theme Files... 5

More information

DATA WAREHOUSE BASICS

DATA WAREHOUSE BASICS DATA WAREHOUSE BASICS A Software Overview using the Retail Golf Model with version 9 NOTE: This course material was developed using Hummingbird version 9 with Windows XP. There will be navigational differences

More information

CSC 415 ONLINE PHOTOALBUM: THE SEQUEL ASP.NET VERSION

CSC 415 ONLINE PHOTOALBUM: THE SEQUEL ASP.NET VERSION CSC 415 ONLINE PHOTOALBUM: THE SEQUEL ASP.NET VERSION GODFREY MUGANDA In this project, you will convert the Online Photo Album project to run on the ASP.NET platform, using only generic HTTP handlers.

More information

Visual C# Program: Simple Game 3

Visual C# Program: Simple Game 3 C h a p t e r 6C Visual C# Program: Simple Game 3 In this chapter, you will learn how to use the following Visual C# Application functions to World Class standards: Opening Visual C# Editor Beginning a

More information

Authoring World Wide Web Pages with Dreamweaver

Authoring World Wide Web Pages with Dreamweaver Authoring World Wide Web Pages with Dreamweaver Overview: Now that you have read a little bit about HTML in the textbook, we turn our attention to creating basic web pages using HTML and a WYSIWYG Web

More information

Start Visual Studio, start a new Windows Form project under the C# language, name the project BalloonPop MooICT and click OK.

Start Visual Studio, start a new Windows Form project under the C# language, name the project BalloonPop MooICT and click OK. Start Visual Studio, start a new Windows Form project under the C# language, name the project BalloonPop MooICT and click OK. Before you start - download the game assets from above or on MOOICT.COM to

More information

Python Working with files. May 4, 2017

Python Working with files. May 4, 2017 Python Working with files May 4, 2017 So far, everything we have done in Python was using in-memory operations. After closing the Python interpreter or after the script was done, all our input and output

More information

Capturing the Mouse. Dragging Example

Capturing the Mouse. Dragging Example Capturing the Mouse In order to allow the user to drag something, you need to keep track of whether the mouse is "down" or "up". It is "down" from the MouseDown event to the subsequent MouseUp event. What

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG 1 Notice Class Website http://www.cs.umb.edu/~jane/cs114/ Reading Assignment Chapter 1: Introduction to Java Programming

More information

Appendix A Programkod

Appendix A Programkod Appendix A Programkod ProgramForm.cs using System; using System.Text; using System.Windows.Forms; using System.Net; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic;

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

ACE Operation Manual

ACE Operation Manual ACE Operation Manual Elecsys Director ACE Operation Manual Product Information Full information about other Elecsys products is available on our website at www.elecsyscorp.com Useful Contact Information

More information

Chapter 8 Advanced GUI Features

Chapter 8 Advanced GUI Features 159 Chapter 8 Advanced GUI Features There are many other features we can easily add to a Windows C# application. We must be able to have menus and dialogs along with many other controls. One workhorse

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

COMSC-031 Web Site Development- Part 2

COMSC-031 Web Site Development- Part 2 COMSC-031 Web Site Development- Part 2 Part-Time Instructor: Joenil Mistal December 5, 2013 Chapter 13 13 Designing a Web Site with CSS In addition to creating styles for text, you can use CSS to create

More information

The Microsoft.NET Framework

The Microsoft.NET Framework Microsoft Visual Studio 2005/2008 and the.net Framework The Microsoft.NET Framework The Common Language Runtime Common Language Specification Programming Languages C#, Visual Basic, C++, lots of others

More information

Introduction to UNIX. Logging in. Basic System Architecture 10/7/10. most systems have graphical login on Linux machines

Introduction to UNIX. Logging in. Basic System Architecture 10/7/10. most systems have graphical login on Linux machines Introduction to UNIX Logging in Basic system architecture Getting help Intro to shell (tcsh) Basic UNIX File Maintenance Intro to emacs I/O Redirection Shell scripts Logging in most systems have graphical

More information

C# Continued. Learning Objectives:

C# Continued. Learning Objectives: Learning Objectives: C# Continued Open File Dialog and Save File Dialog File Input/Output Importing Pictures from Files and saving Bitmaps Reading and Writing Text Files Try and Catch Working with Strings

More information

1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are

More information

DATA STRUCTURE AND ALGORITHM USING PYTHON

DATA STRUCTURE AND ALGORITHM USING PYTHON DATA STRUCTURE AND ALGORITHM USING PYTHON Advanced Data Structure and File Manipulation Peter Lo Linear Structure Queue, Stack, Linked List and Tree 2 Queue A queue is a line of people or things waiting

More information

Test Requirement Catalog. Generic Clues, Developer Version

Test Requirement Catalog. Generic Clues, Developer Version Version 4..0 PART 1: DATA TYPES Test Requirement Catalog SIMPLE DATA TYPES... 4 BOOLEAN... 4 CASES... 4 COUNTS... 5 INTERVALS... 5 [LOW, HIGH] an interval that contains both LOW and HIGH... 6 [LOW, HIGH)

More information

Your First Windows Form

Your First Windows Form Your First Windows Form From now on, we re going to be creating Windows Forms Applications, rather than Console Applications. Windows Forms Applications make use of something called a Form. The Form is

More information

Smoother Graphics Taking Control of Painting the Screen

Smoother Graphics Taking Control of Painting the Screen It is very likely that by now you ve tried something that made your game run rather slow. Perhaps you tried to use an image with a transparent background, or had a gazillion objects moving on the window

More information

Lecture # 7 Engr. Ali Javed 18th March, 2014

Lecture # 7 Engr. Ali Javed 18th March, 2014 Lecture # 7 Engr. Ali Javed 18 th March, 2014 Instructor s Information Instructor: Engr. Ali Javed Assistant Professor Department of Software Engineering U.E.T Taxila Email: ali.javed@uettaxila.edu.pk

More information

Menus. You ll find MenuStrip listed in the Toolbox. Drag one to your form. Where it says Type Here, type Weather. Then you ll see this:

Menus. You ll find MenuStrip listed in the Toolbox. Drag one to your form. Where it says Type Here, type Weather. Then you ll see this: Menus In.NET, a menu is just another object that you can add to your form. You can add objects to your form by drop-and-drag from the Toolbox. If you don t see the toolbox, choose View Toolbox in the main

More information

Introduction to Linux

Introduction to Linux Introduction to Linux The command-line interface A command-line interface (CLI) is a type of interface, that is, a way to interact with a computer. Window systems, punched cards or a bunch of dials, buttons

More information

LookoutDirect Basics: Windows, Tools, Files, and Path Names

LookoutDirect Basics: Windows, Tools, Files, and Path Names LookoutDirect Basics: Windows, Tools, Files, and Path Names 4 Starting LookoutDirect Logging on to LookoutDirect This chapter explains how to start and get around within LookoutDirect. It describes the

More information

IST311 Chapter13.NET Files (Part2)

IST311 Chapter13.NET Files (Part2) IST311 Chapter13.NET Files (Part2) using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text;

More information

XDS An Extensible Structure for Trustworthy Document Content Verification Simon Wiseman CTO Deep- Secure 3 rd June 2013

XDS An Extensible Structure for Trustworthy Document Content Verification Simon Wiseman CTO Deep- Secure 3 rd June 2013 Assured and security Deep-Secure XDS An Extensible Structure for Trustworthy Document Content Verification Simon Wiseman CTO Deep- Secure 3 rd June 2013 This technical note describes the extensible Data

More information

Introduction to File Systems

Introduction to File Systems Introduction to File Systems CS-3013 Operating Systems Hugh C. Lauer (Slides include materials from Slides include materials from Modern Operating Systems, 3 rd ed., by Andrew Tanenbaum and from Operating

More information

Conventions in this tutorial

Conventions in this tutorial This document provides an exercise using Digi JumpStart for Windows Embedded CE 6.0. This document shows how to develop, run, and debug a simple application on your target hardware platform. This tutorial

More information

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio Introduction XXV Part I: C# Fundamentals 1 Chapter 1: The.NET Framework 3 What s the.net Framework? 3 Common Language Runtime 3.NET Framework Class Library 4 Assemblies and the Microsoft Intermediate Language

More information

Bits, Words, and Integers

Bits, Words, and Integers Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

The QuickCalc BASIC User Interface

The QuickCalc BASIC User Interface The QuickCalc BASIC User Interface Running programs in the Windows Graphic User Interface (GUI) mode. The GUI mode is far superior to running in the CONSOLE mode. The most-used functions are on buttons,

More information

1 sur 26 13/12/2011 15:18 2 sur 26 13/12/2011 15:18 Introduction The File API provides an interface with the server's OS File system. It allows you to handle files and folders as JavaScript objects using

More information

// Program 2 - Extra Credit // CIS // Spring // Due: 3/11/2015. // By: Andrew L. Wright. //Edited by : Ben Spalding

// Program 2 - Extra Credit // CIS // Spring // Due: 3/11/2015. // By: Andrew L. Wright. //Edited by : Ben Spalding // Program 2 - Extra Credit // CIS 200-01 // Spring 2015 // Due: 3/11/2015 // By: Andrew L. Wright //Edited by : Ben Spalding // File: Prog2Form.cs // This class creates the main GUI for Program 2. It

More information

Caja File Manager. Desktop User Guide

Caja File Manager. Desktop User Guide Caja File Manager Desktop User Guide Desktop User Guide» Working with Files This chapter describes how to use the Caja file manager. Introduction Spatial Mode Browser Mode Opening Files Searching For Files

More information

6.001 Notes: Section 17.5

6.001 Notes: Section 17.5 6.001 Notes: Section 17.5 Slide 17.5.1 Now, let's look at one example in which changing the evaluation model allows us to explore a very different kind of computational problem. Our goal is to show how

More information

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp Overview CSE 143 Topics Data representation bits and bytes Streams communicating with the outside world Basic Java files Other stream classes Streams Reading: Ch. 16 4/27/2004 (c) 2001-4, University of

More information