Stream when you use vb.net to read and write files for the first time, you will surely find that vb.net discard traditional file I/O support and feel unaccustomed. In fact, in. NET, Microsoft has replaced traditional file operations with rich "streaming" objects, and "streaming" is a Unix objects that are often used inside. we can think of a stream as a channel through which data can be "streamed" to various data storage institutions (such as files, strings, arrays, or other forms of flow). Why do we discard the long IO operation and the stream? One of the important reasons is that not all data exists in the file. Now, the program takes data from various types of data stores, such as a file, a buffer in memory, and the Internet. Streaming technology allows an application to get a variety of data based on a programming model without having to learn how to get the specific technology of a file on a remote Web server. We just need to create a stream between the application and the Web server, and then read the data sent by the server. Stream objects, encapsulating the various operations of reading and writing data sources, the biggest advantage is that when you learn how to operate a data source, you can extend this technology to other kinds of data sources. type of Flow A stream is an abstract class, and you cannot declare an instance of the stream in a program. Within. NET, 5 specific streams are derived from the stream, respectively,
FileStream supports sequential and random read and write operations on files MemoryStream supports sequential and random read-write operations on memory buffers NetworkStream supports sequential and random read and write operations on Internet network resources, existing in System.Net.Sockets namespaces CryptoStream supports encoding and decoding of data, existing in System.Security.Cryptography namespaces BufferedStream supports buffered read-write to objects that are not supported by themselves not all streams take the same approach, such as reading a stream of local files, you can tell us the length of the file, the current read-write location, and so on, you can use the Seek method to jump to any location in the file. In contrast, streams that read remote files do not support these attributes. However, the stream itself has CanSeek, CanRead, and CanWrite attributes that distinguish the data source and tell us whether to support or not support an attribute. Here we briefly introduce a FileStream class FileStream class In the local file operation, we can use the Filesteam class, can be very simple read and write as a byte array (arrays of bytes). For reading and writing data of simple data types, you can use BinaryReader and BinaryWriter as well as streamreader,streamwriter classes. BinaryReader, a primitive data type is read as a binary value with a specific encoding. BinaryWriter writes a primitive type to the stream in binary form and supports writing a string with a specific encoding. Streamreader/writer stores the data in XML format. There is little difference in vb.net, because the classes used are applied to both formats. VB. NET supports traditional random read and write files, you can create files for storing struct, and then access them according to the number of records. As in previous versions of VB, use the Fileopen,fileget function. To a large extent, this has been replaced by XML or a database. If you create a new application and there is no need to consider compatibility issues with the version, it is recommended. NET's new features. whatever you are going to use to get a streamclass, you have to create a FileStream object. There are many ways to create, the simplest is to specify the file path, open the mode, such as the following syntax. Dim FStream as New FileStream (path, FileMode, FileAccess) Path to include file paths and file names. FileMode is one of the members of the enumeration type FileMode, as shown in the following table. FileAccess is a member of the enumeration type FileAccess. Read (read only), ReadWrite (read-write), and write (writes). Determines the read and write permissions of the file.
Member name |
Description |
Append |
Open an existing file and find the end of the file, or create 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 the file (if the file exists), otherwise, create a new file. |
Truncate |
Specifies that the operating system should open an existing file. Once the file is opened, it will be truncated to a size of 0 bytes. |
of course, you can also use (Open, OpenRead, OpenText, Openwrite) to create FileStream Dim FS as New FileStream = IO. File.openwrite ("C:\Stream.txt") another way to open a file is to use the OpenFile method of the OpenFileDialog and SaveFileDialog controls. you do not need to specify any parameters. The OpenFileDialog OpenFile method opens the file in read-only mode; The SaveFileDialog OpenFile method opens the file in read-write mode. FileStream supports only the most basic operations, writing data to a byte array or writing to a file from a byte array. If we use FileStream to save the data in a file, we first convert the data to a byte array, and then call the FileStream write method. Similarly, the FileStream read method returns a byte array. You may not always use FileStream objects directly, we still need to take a look at its basic functions After you create the FileStream object, call WriteByte to write a byte into the file. The Write method can write an array to a file, requiring three parameters Write (buffer, offset, count) buffer is to write to the array address, offset is offset, count refers to the number of bytes written, read syntax is the same. since FileStream to deal with bytes array, it is necessary to study asciiencoding GetBytes and UnicodeEncoding GetChars. The following example is a conversion operation. Dim buffer () as Byte Dim Encoder as New System.Text.ASCIIEncoding () Dim str as String = " This are a line of text" ReDim buffer (str. LENGTH-1) encoder.getbytes (str, 0, str.) Length, buffer, 0) FS. Write (buffer, 0, buffer.) Length) Note: You must resize the byte array to write to read-write length.
flexible and diverse
IO
operation
Sometimes, converting between data and byte arrays is a tedious task. To avoid these tedious transformations and simplify the code, useStreamreader/streamwriteandBinaryreader/binarywriterworthy of the wise. Streamreader/streamwriterespectively byTextreader/textwriterclass, which automatically performs a byte-encoded conversion. Binaryreader/binarywriterbyStreamderives mainly from reading and writing data in binary form. when you read data from a binary file, you first create aBinaryReaderthe instance,BinaryReaderThe build function accepts aFileStreamobject that represents the file that will be read. We've seen it before, we can use it.
File.openread or
File.openwrite method createsFileStreamobject. the following are as follows:Dim BR as New IO. BinaryReader (IO. File.openread (path))Dim BW as New IO. BinaryWriter (IO. File.openwrite (path))BinaryWriterclass has
Writeand
WriteLinein two ways, you can accept any type of data as a parameter to write to a file (
WriteLineappends a row of data to the end of a file. BinaryReaderclass has many methods of reading data, data stored on the file, and there is no information about their type, so read the data, you must select the appropriate overloadReadmethod. The following example assumesBwis an already initializedBinaryWriterobject that represents how to write a string, integer, and double-precision number to a file:BW. WriteLine ("A String")BW. WriteLine (12345)BW. WriteLine (123.456789999999)when you read back the data, you have to chooseBinaryReaderthe appropriate Read method:Dim s as String = BR. ReadString ()Dim i as Int32 = BR. ReadInt32 ()Dim dbl as Double = BR. Readdouble ()for text files, useStreamreader/streamwriterobject. method is similar to the above, write the data with the sameWriteandWriteLinemethod. Readmethod to read a character,ReadLineread one row of data (until there is a carriage return/line break),ReadToEndread all the characters to the end of the file.
Object Serialization
so far, we've just written simple types of data into a file and read back to the program. In fact, most programs read and write data may not be simple types, but complex structures, such as: arrays, array lists, hash tables and so on. So we take a technique of serialization, first converting the value of the array into a byte sequence, and then writing the file so that the entire array is stored. Instead, we call it deserialization. Serialization is. NETa very big topic, this column introduces the basic information. UseBinaryFormatterof the
Serialize and
Deserializemethod to save an object to a file and a read-back program. First,Imports System.RunTime.Serialization.Formatters, lest write so long a statement. FormattersThe name space containsBinaryFormatterclass, which is used to serialize objects in binary data. CreateBinaryFormatterinstance, and then calls the
Serializemethod,
Serializeaccept two parameters: one is writableFileStreaminstance, the file used to hold the data;the other one is the object itself:Dim Binformatter as New binary.binaryformatter ()Dim R as New Rectangle (a)binformatter.serialize (FS, R) BinaryFormatterof the
Deserializemethod has only one argument,FileStreaminstance. In the current position, deserialization gets an object of unknown type, we must useCtypeconverted to the original object. The following example deserializes the file above to get the originalRectangleobjects:Dim R as New Rectangle ()R = CType (Binformatter.deserialize (FS), Rectangle)we can also takeXmlformatterobjects are serialized. First inIdeof theProjectMenu Selection AddSystem.Runtime.Serialization.Formatters.Soap, and then you can createSoapFormatterobject, the method is the same as Binformatter, except that the data is stored in XML format:Dim FS as New IO. FileStream ("C:\Rect.xml", IO. FileMode.Create, IO. FileAccess.Write)Dim Xmlformatter as New SoapFormatter ()Dim R as New Rectangle (8, 8, 299, 499)xmlformatter.serialize (FS, R)Open C:\Rect.xml , which actually stores the content:
-<soap-env:envelope xmlns:xsi= "
http://www.w3.org/2001/XMLSchema-instance"Xmlns:xsd="
Http://www.w3.org/2001/XMLSchema"Xmlns:soap-enc="
http://schemas.xmlsoap.org/soap/encoding/"Xmlns:soap-env="
http://schemas.xmlsoap.org/soap/envelope/"Xmlns:clr="
http://schemas.microsoft.com/soap/encoding/clr/1.0"Soap-env:encodingstyle="
http://schemas.xmlsoap.org/soap/encoding/">
-<SOAP-ENV:Body>
-<a1:rectangle id= "
ref-1"Xmlns:a1="
http://schemas.microsoft.com/clr/nsassem/System.Drawing/System.Drawing%2C%20Version%3D1.0.3300.0%2C% 20CULTURE%3DNEUTRAL%2C%20PUBLICKEYTOKEN%3DB03F5F7F11D50A3A">
<x>
8</x>
<y>
8</y>
<width>
249</width>
499
</a1:Rectangle>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
specific examples of file operations
In this section, you will find more common code examples of file operations. The most common, most basic operation is to write text to the file and read back. Today's applications typically use binary files instead of storing simple variables, which are used to store objects, collections of objects, and other machine code. Below, you will see examples of specific actions.
Read and write text files
To save text to a file, create a StreamReader object based on FileStream, and then call the Write method to write the text that needs to be saved to the file. The following code prompts the user with SaveFileDialog to specify a file to hold the contents of TextBox1. savefiledialog1.filter = _ "Text files|*.txt| All Files|*.* " savefiledialog1.filterindex = 0 If Savefiledialog1.showdialog = DialogResult.OK then Dim FS as FileStream = savefiledialog1.openfile Dim SW as New StreamWriter (FS) SW. Write (TextBox1.Text) SW. Close () FS. Close () end if Similarly, we read a text file and display the contents in a TextBox control. The StreamReader ReadToEnd method returns the entire contents of the file. openfiledialog1.filter = _ "Text files|*.txt| All Files|*.* " openfiledialog1.filterindex = 0 If Openfiledialog1.showdialog = DialogResult.OK then Dim FS As filestream FS = openfiledialog1.openfile Dim SR as New StreamReader (FS) TextBox1.Text = SR. readtoend SR. Close () FS. Close () end If
Storage of various objects
A specific object can be serialized using Binaryformatte in binary form, or in XML format using the SoapFormatter class. As long as you change all BinaryFormatter references to SoapFormatter, you can serialize the objects in XML format without changing any code. First create a BinaryFormatter instance: Dim binformatter As New Binary.binaryformatter () and then create a FileStream object to store the serialized object: Dim FS As New S Ystem. Io. FileStream ("C:\test.txt", IO. FileMode.Create) then invokes the Binformatter
SerializeMethod serializes any framework object that can be serialized: R = New Rectangle (rnd. Next (0), Rnd. Next (0, Rnd), _. Next (a), Rnd. Next (1, 9)) Binformatter.serialize (FS, R) plus a Serializable property allows the custom object to serialize <serializable () > Public Structure Pers On Dim Name As String Dim age as Integer Dim income as Decimal end Structure The following code creates an instance of the person object and then calls the BI Nformatter's
SerializeMethod serializes the Custom object: p = New person () P.name = "Joe Doe" p.age = P.income = 28500 binformatter.serialize (FS, P) You can also be in the same Stream, then the other objects are serialized and then read back in the same order. For example, after the person object is serialized, a Rectangle object is serialized: Binformatter.serialize (FS, New Rectangle (0, 0, 100, 200)) creates a BinaryFormatter object , call its
Deserializemethod, and then converts the returned value to the correct type, which is the entire deserialization process. Then it then sends the other objects that serialize the stream. Assuming that the person and the rectangle two objects have been serialized, in the same order, we can deserialize the original object by deserializing it:
Dim p As New Person () P = binformatter.serialize (fs, person) Dim R As New Rectangle r = Binformatter.serialize (FS, R Ectangle)
Persisting Collections
Storage of Collections
Most programs work with collections of objects rather than individual objects. For collection data, it is easy to create an array (or other type of collection, such as ArrayList or Hashtable), populate with objects, and then a serialize method can serialize the whole collection. For the following example, first create a ArrayList with two person objects, and then serialize itself:
Dim FS as New System.IO.FileStream _ ("C:\test.txt", IO. FileMode.Create) Dim binformatter As New Binary.binaryformatter () Dim P As New Person () Dim Persons As New ArrayList p = new person () P.name = ' Person 1 ' p.age = P.income = 32000 persons.add (p) p = new person () P.name = "Person 2" p.age = P.income = 72000 persons.add (P) binformatter.serialize (FS, Persons) call a B for a file that stores the serialized data as a parameter Inaryformatter instance of
Deserializemethod, you return an object and then convert it to the appropriate type. The following code deserializes all objects in the file and then processes all the person objects: FS = New System.IO.FileStream _ ( "C:\test.txt", IO. FileMode.OpenOrCreate) Dim obj As object Dim P As Person (), R as Rectangle () do & nbsp; obj = binformatter.deserialize (FS) If obj. GetType is GetType (person) then P = CType (obj, person) ' Process the P objext End if Loop while FS. Position < FS. length-1 FS. Close () The following example invokes the deserialize method to deserialize the entire collection and then converts the return value to the appropriate type (person): FS = New System.IO.FileStream ("C:\test.txt ", IO. FileMode.OpenOrCreate) Dim obj As object Dim Persons As New arraylist obj = CType (binf Ormatter. Deserialize (FS), ArrayList) FS. Close ()