注册会员,创建你的web开发资料库,i/o classes to understand how to carry out the reading and writing of data using the i/o classes, we will create a new asp.net web application in visual c# using the file -> new project dialog box. we will name the project ioexamples as shown in the following diagram:
we will kick off our demonstration of the i/o classes by considering the classes that are related to performing file system operations. file system operations as discussed before, the classes that are used to browse around the file system and perform operations like moving, copying, and deleting files, can be broadly classified into two categories.
classes that expose static or shared methods, e.g. file and directory. if you want to only do operations on a folder or a file then using the file or directory class is more efficient as it saves us the overhead of instantiating a .net class.
classes that expose instance methods. e.g. fileinfo and directoryinfo. these classes can be used to perform the same set of functions as the file and directory classes except that we need to create an instance of them to be able to do so. these classes will be very efficient if you are performing multiple operations using the same object, because they will read in the authentication and other information for the appropriate file system object at the time of the construction of the object. once this information is read and stored as part of the object, it need not be read every time a method call is made.
to demonstrate the implementation of the file system related classes, let us consider the following example:
when the user selects the file using the browse dialog box, and clicks get attributes, we execute the code shown below. we start by getting the name of the selected file from the form element named fileopener, and putting it into a local variable named filename. then we create an instance of the fileinfo object, passing to it the full path of the selected file. we then invoke its properties and methods to display the attributes of the selected file. private void bntgetattributes_click(object sender, system.eventargs e) { //clear the listbox lstattributes.items.clear(); //get the name of the selected file string filename = fileopener.value; //set the label to display the selected file lblmessage.text = "selected file is :" + filename; fileinfo fileinfo = new fileinfo(filename); lstattributes.items.add("the file attributes are : " ); lstattributes.items.add(" name = " + fileinfo.name); lstattributes.items.add(" creation time = " + fileinfo.creationtime); lstattributes.items.add(" last access time = " + fileinfo.lastaccesstime.tostring()); lstattributes.items.add(" directory name = " + fileinfo.directoryname); lstattributes.items.add(" length = " + fileinfo.length.tostring()); lstattributes.items.add("..........."); we then get the name of the parent directory of the selected file, and create an instance of the directoryinfo object using the directory name as the argument. once we create an instance of the directoryinfo object, we can then display the attributes of the directory. string dirname = fileinfo.directoryname; directoryinfo dirinfo = new directoryinfo(dirname); lstattributes.items.add("the directory attributes are : " ); lstattributes.items.add(" name = " + dirinfo.name); lstattributes.items.add(" root name = " + dirinfo.root.name); lstattributes.items.add("..........."); lstattributes.items.add("all the files contained in the directory are : " ); we also display all of the child files contained in the directory by looping through the array of fileinfo objects returned by the getfiles method. foreach(fileinfo fileinfochild in dirinfo.getfiles()) { lstattributes.items.add(fileinfochild.name); }
lstattributes.items.add("..........."); lstattributes.items.add("all the subdirectories contained in the directory are : " ); finally we display all the directories contained in the directory by enumerating through the directoryinfo 's array returned by the getdirectories method. foreach(directoryinfo dirinfochild in dirinfo.getdirectories()) { lstattributes.items.add(dirinfochild.name); } } this method is used to copy over the selected file from its current directory to the application path. private void bntcopyfile_click(object sender, system.eventargs e) { //clear the listbox lstattributes.items.clear(); //get the full path of the selected file string sourcepath = fileopener.value; //set the label to display the selected file lblmessage.text = "selected file is :" + sourcepath; //get the file name alone from the string string filename = path.getfilename(sourcepath); string destpath = server.mappath(request.applicationpath) + "//" + filename ; //copy the file to the current application path file.copy(sourcepath,destpath,true); lstattributes.items.add(" the file " + filename + " has been copied from " ); lstattributes.items.add(sourcepath); lstattributes.items.add(" to " + destpath); } we use this method to move the selected file from its current location to the application path. private void btnmovefile_click(object sender, system.eventargs e) { //clear the listbox lstattributes.items.clear(); //get the full path of the selected file string sourcepath = fileopener.value; //set the label to display the selected file lblmessage.text = "selected file is :" + sourcepath; string filename = path.getfilename(sourcepath); string destpath = server.mappath(request.applicationpath) + "//" + filename ; //move the file to the current application path file.move(sourcepath,destpath); lstattributes.items.add(" the file " + filename + " has been moved from " ); lstattributes.items.add(sourcepath); lstattributes.items.add(" to " + destpath); } in this method, we get the selected file and delete it from its current location. private void btndeletefile_click(object sender, system.eventargs e) { //clear the listbox lstattributes.items.clear(); //get the full path of the selected file string sourcepath = fileopener.value; //set the label to display the selected file lblmessage.text = "selected file is :" + sourcepath; string filename = path.getfilename(sourcepath); //delete the file file.delete(sourcepath); lstattributes.items.add(" the file " + filename + " has been deleted from " ); lstattributes.items.add(sourcepath); } path since the path class contains only static methods, its methods can be accessed without having to create an instance of it. the methods exposed by the path class are mainly used to manipulate path names in a platform-independent manner. using the path class is a whole lot easier than trying to fiddle about with path separation characters manually, especially because the path class encapsulates the different formats for path names on different operating systems. the following example illustrates the different important properties and methods of the path class. the web form we are going to use for the demonstration looks like this:
once you select the file name using the browse file open dialog box and click get path attributes, we execute the following lines of code: private void bntgetattributes_click(object sender, system.eventargs e) { //clear the listbox lstattributes.items.clear(); string filename = fileopener.value; //set the label to display the file name lblmessage.text = "the file you have selected is " + filename; //display the properties in the listbox lstattributes.items.add(" file name = : " + path.getfilename(filename)); lstattributes.items.add(" directory name = " + path.getdirectoryname(filename)); lstattributes.items.add(" extension = " + path.getextension(filename)); lstattributes.items.add(" file name without extension = " + path.getfilenamewithoutextension(filename)); lstattributes.items.add(" root path = " + path.getpathroot(filename));lstattributes.items.add(" has extension = " + path.hasextension(filename).tostring()); lstattributes.items.add(" path separator = " + path.pathseparator); lstattributes.items.add("directory separator = " + path.directoryseparatorchar); lstattributes.items.add("alt directory separator = " + path.altdirectoryseparatorchar); lstattributes.items.add("temporary folder name = " + path.gettemppath()); } in the code presented above, we get the name of the file that the user has selected by using the following line: string filename = fileopener.value; once we get the file name, we pass this as an argument to the static members of the path class and show the results in the list box. binaryreader and binarywriter when we work with streams of binary data, we often need to read and write primitive types. the system.io namespace provides binaryreader and binarywriter classes to accomplish this. using the binarywriter class, we can not only write data that belongs to any of the primitive types, but also specify the type of encoding to be used for writing. similar to the binarywriter class, the binaryreader exposes properties and methods to read primitive data types as binary values. some of the important methods that provide this functionality include: readboolean, readbyte, readchar, readdecimal, readdouble, readint16, readint32, readint64, readstring, readsingle, and so on. from the names of the methods, we can easily figure out the kind of data each method is designed to handle. let us consider the following example for the illustration of writing of data using the binarywriter class. in this example, we write primitive types such as a string, an int, a single, and a decimal to the file. private void page_load(object sender, system.eventargs e) { // put user code to initialize the page here string filename = server.mappath("binaryfile.txt"); //create the filestream object with the proper settings filestream stream = new filestream(filename,filemode.append,fileaccess.write); //associate the filestream with the binaryreader binarywriter writer = new binarywriter(stream); writer.write("this is a string value"); writer.write(1233); writer.write(1.8f); writer.write(90.1m); stream.flush(); stream.close(); } to read the file created by the above example, we will use the binaryreader class. here we invoke the different forms of read method such as readstring, readint16, readsingle, and readdecimal to read primitive types from the file. we then display the read contents in the list box named lstcontents: private void bntreaddata_click(object sender, system.eventargs e) { string filename = server.mappath("binaryfile.txt"); //create the filestream object with the proper settings filestream stream = new filestream(filename,filemode.open,fileaccess.read); //associate the filestream with the binaryreader binaryreader reader = new binaryreader(stream); //read the primitive types from the file lstcontents.items.add(reader.readstring()); lstcontents.items.add(reader.readint16().tostring()); lstcontents.items.add(reader.readsingle().tostring()); lstcontents.items.add(reader.readdecimal().tostring()); stream.flush(); stream.close(); } streamreader and streamwriter as mentioned before, these classes are used to read and write data that is in character format. they are mainly useful in cases when we are trying to read from or write data to a text file. when constructing a streamreader, we need to provide values for the following options.
encoding method: in this parameter, we need to specify what to do about the different encoding methods. there are two ways by which we can do this. we can either let the streamreader examine the byte order marks in the file to determine the encoding method, or we can simply tell the streamreader to assume that the file uses a specified encoding method.
reference to another stream: instead of supplying a file name to be read from, we can supply a reference to another stream. this option is very important as it demonstrates the advantage of basing our model for reading and writing data around the concept of streams. this is useful in situations where you have another stream that contains the actual data, and you want to process the data contained in that stream in your application. we can easily carry this out by passing the output of that stream to a streamreader constructor and start using it.
for example, the following line of code shows how to construct a simple streamreader object. we pass in the file name to be read and the encoding to be assumed as arguments, to the constructor of the streamreader object. streamreader reader = new streamreader(@"c:/test.txt",encoding.utf8); in the later stages of this article, when we look at the filestream class, we will see how we can hook a streamreader object up to a filestream object to read data from a text file. the following list shows some of the important methods of the streamreader class:
read - allows us to read the next character or a set of next characters from the input stream.
readblock - allows us to read a block of characters into the buffer.
readtoend - as the name suggests, this provides the ability to read character data from the current stream until the end.
readline - permits us to read a single line of characters from the current stream.
peek - it is similar to the read method except for the difference that it does not advance the current character position.
the streamwriter class works basically the same as the streamreader class, except that it is used to write to a text file. the streamwriter class exposes the following methods to accomplish this: write and writeline. the following simple example shows how to read and write to a text file using the streamreader and streamwriter classes. first off, we create a streamwriter object and associate it with a file named streamwriterfile.txt. we then write few lines of text using the writeline method. finally we flush the contents and close the streamwriter object. private void page_load(object sender, system.eventargs e) { //create the streamwriter object with the proper settings streamwriter writer = new streamwriter(server.mappath("streamwriterfile.txt"),true); writer.writeline("programming languages :"); writer.writeline("asp.net"); writer.writeline("visual c#"); writer.writeline("visual basic.net"); writer.writeline("jscript.net"); writer.writeline("ado.net"); writer.flush(); //close the streamwriter writer.close(); in the following block of code, we read the lines of text written by the above code and write them to the client browser: //create the streamreader object streamreader reader = new streamreader(server.mappath("streamwriterfile.txt")); response.write(reader.readline() + "<br>"); response.write(reader.readline()+ "<br>"); response.write(reader.readline() + "<br>"); response.write(reader.readline()+ "<br>"); response.write(reader.readline() + "<br>"); response.write(reader.readline()+ "<br>"); //close the reader reader.close(); }