Oct 28, 2011

Reading and writing files in c #


File management on the platform. NET is achieved through the Stream class that represents an information flow (A file is considered a data stream, as the data transferred from one device to another, or the data transferred over the network TCP / IP).
The Stream class is an abstract class, so you can not use it directly and can not be instantiated. What you should do is use one of its derived classes that specialize in the treatment of streams to different destinations such as FileStream (file management), MemoryStream (for in-memory data management, etc.).
The first choice for writing and / or read data from a text file using the FileStream class. This class is in the System.IO namespace and a class derived from the Stream class.
The FileStream acts as an intermediary between the file system and our application, enabling a clean and easily read and write operations on files. To use the FileStream, the first thing to do is create an instance that points to the desired file. For this you have the option of using one of the builders offered, as follows:

As shown in the figure above, is a builder rather tedious to use because a considerable amount of parameters. To counter this, we are able to use any of the methods offered by the utility class File, which allows us to obtain a FileStream with specific parameters according to the method used to obtain it. Below is an example:

In the above example we used the Create method that creates the file in the specified path and if the file exists, it is overwritten. These methods offered by the File class, facilitate the development of records management applications and enables a better readability of code.
To write data to a text file, using the methods Write and WriteByte. The former receives as a parameter an array of bytes that represents the information to be stored, while the second receives as a parameter a single byte to be written. Choose which of the two methods used depends on the scenario, because when you go to write a lot of information, it is advisable to write byte by byte because it is executed many times the same cycle but on the contrary, it is convenient to write several bytes time.
Below is an example of the write operation with both methods:

It can be observed using the Encoding class to format the string in UTF8 and get the array of bytes to be written to the file. In the same way you can encode the text to write in another format such as ASCII, Unicode, etc..
It is noteworthy that all streams should be closed at the end of the operation performed on it, because otherwise the file would be blocked and will not be released operating system resources. Additionally, the Flush method is used to tell the FileStream class, you type in the physical file that has been written with the method or the method WriteByte Write to date as otherwise such changes will be reflected only when you close the Stream. This method would be useful when we want to enter text in the file and do not want to close the Stream because we need to continue to write operations, as well as being a good practice to always use it even when it seems unnecessary.
The implementation of the same functionality with the other method, would be as shown below.

As shown in the example above, with these methods, the programmer has a very precise control over the information you want to write to the file, therefore, that it may even sometimes be cumbersome.
Fortunately, the. NET offers other ways to manage Streams to make life easier for the developer. One of those ways is to use the StreamWriter class to write to files and StreamReader to read from. It is necessary to note that these classes are designed to get characters to output as opposed to classes that inherit from Stream are designed to get bytes.
With the StreamWriter class, we should only worry about using the Write or WriteLine method to write data to a text file. These methods are native data types such as language int, bool, decimal, float, string, char, etc. And use the encoder indicated when the class instance to encode characters into the text file output. If you use a constructor that specifies some Encoding, by default this class operates with UTF8..

As shown in the example above, the lines of code are much simpler than those seen in the example of the FileStream. This is because the StreamWriter class is a class specialized for the work stream for text files and saves you the trouble of having to get the byte representation of the value we want to write.
The difference between Write and WriteLine method is that the second inserts a line break at the end of the input data, making the next time you want to insert, made in the next line.
Although the StreamWriter class does not inherit from the Stream class, if used in a Stream in its implementation which writes or reads strings. Therefore, within this class is responsible for creating and using the Stream need to point to the text file represented by the path that was used in the constructor for example. However, this class also has another builder where you can spend a Stream we have created instead of the path, as shown below:

Complementing the StreamWriter is the StreamReader object, whose main objective is to facilitate the tasks of reading character strings. For this purpose, we can unconcerned these low-level tasks in order to get a much cleaner code and easily legible.

The example shows how easily you can read information from a text file using the ReadLine method of StreamReader object. This method simply reads the next line taking into account the current position of file pointer.
It is important to note that using the streams seen so far you can read and write text files strings, ie plain text. This implies that the written information in the files can be seen and understood by anyone, as it is saved as is in the beginning.
This can be a problem where you choose to use text files as a data repository application (although this is not recommended, there will be cases may become necessary), and say it's a problem because there might be information that does not want that anyone can see it, much less understand, but we would like that information was stored securely.
One possible option for this is storing information in binary format, ie that the information is stored not in plain text format but in its binary representation (1s and 0s), which allows for more privacy (EYE, only more privacy , not much privacy or security. If the point was how to get a safe way to store information would have to look at the issues of encryption and hashing). In. NET, the object that enables us to work with binary data stream is the BinaryWriter and BinaryReader, which I guess can be deducted as they are used as seen above.
The first allows write data to a text file in binary format using the method Write (), the cual.tiene several overloads among which supports multiple data types such as int, long, bool, double, decimal, char, string . The second allows you to retrieve information stored in binary format using the above method. As so via the above method?. What happens to the BinaryReader is that it has a generic Read method, but has a Read to each type of data that can be written, for example ReadInt32, readBoolean, ReadChar, etc.. This requires us to know the structure of the file we are working to read the correct data type in the correct position.
Below is a small example on using the BinaryReader and BinaryWriter.

In the above example shows how to write various types of data with the same BinaryWriter object's Write method as it has several overloads.
Below is the information as seen in the case of trying to view a text editor:

To read binary data using the BinaryReader object and used "the method indicated."
In the above example can be seen as using the method of reading the type of data you want to read, which means that before you know the file structure. In this case, note that was read exactly the same order in which the information was written with the BinaryWriter.
The following is the result of executing the above code:


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes