Three ways to read and write the "Win 10 application Development" file

Source: Internet
Author: User

This article discusses how to read and write files in the old week with your friends. All in all, there are three ways to use it, and each one has its own characteristics and it doesn't say which is better. Anyway, you have to remember the great wisdom that our ancestors left us--there is no way to do it, but to use it flexibly.

OK, let's get started.

First of all: Use the FileIO class.

This class belongs to the RT library API, which exposes a bunch of static methods that can be called directly, quickly and easily, just like the file class in. net. When using the FileIO class, you need to be aware of a storagefile instance that references a known file, and FileIO can only manipulate files that already exist, and it does not automatically create files.

The following code shows how to write text content to a file using the FileIO class.

 //  get document library  Storagefold            ER doclib = knownfolders.documentslibrary;   //  Create a new file  StorageFile NewFile = await  doclib. Createfileasync (  "  //  write text to file  await  fileio.writetextasync (newfile, Content, Unicodeencoding.utf8); 

When reading and writing text, it is strongly recommended to explicitly specify the UTF-8 encoding, which can reduce the probability of the occurrence of supernatural events, believe it or not.
When you call the Createfileasync method to create a new file, you can only set a value for the Creationcollisionoption enumeration at the same time, and if the value is failIfExists, an exception is thrown when the file already exists Here, I choose Openifexists, which is created if the file does not exist, opens the existing file if it exists, and if the value is replaceexisting, replaces the existing file.

The following code reads the text from the file you just saved.

            Try            {                //Accessing the document libraryStoragefolder doclib =knownfolders.documentslibrary; //get the file you just savedStorageFile file =awaitDocLib.                Getfileasync (filename); if(File! =NULL)                {                    //read-in contentDisplaycontent =awaitfileio.readtextasync (file, Unicodeencoding.utf8); }            }            Catch(filenotfoundexception) {displaycontent="The file does not exist. "; }            Catch(Exception ex) {displaycontent=Ex.            Message; }

If the file to be opened does not exist, a FileNotFoundException exception is thrown, so I specifically catch this exception in order to give the user feedback when the file does not exist.
Here is a key point, we have to remember, you write the text with the Utf-8 code, in the read out also use the matching encoding format, in the Civil Affairs Bureau registration certificate, you can not write the name of other people's wife.

The second scenario uses the API for the RT library, which is the DataWriter and DataReader classes. This is different from the FileIO, FileIO for the file object, and DataReader and DataWriter for the stream, file flow, memory flow, network flow can be used, they are targeted to different applications, of course, can be used to read and write file streams.

The following code demonstrates writing the current time to a file.

            //Get document libraryStoragefolder doclib =knownfolders.documentslibrary; //Create a fileStorageFile file =awaitDocLib. Createfileasync ("New.txt", creationcollisionoption.replaceexisting); //Open File Stream            using(Irandomaccessstream stream =awaitfile. OpenAsync (Fileaccessmode.readwrite)) {DataWriter DW=NewDataWriter (stream); //Write TimeDW.                Writedatetime (Datetimeoffset.now); //submit data to a stream                awaitDW.                Storeasync (); // FinishDW.            Dispose (); }

The Openxxxasync method that calls Storagefile can open a stream to read and write files, and if you want the open stream to support write behavior, you should call the Openasync method. and pass the Fileaccessmode.readwrite value in the parameter, the explanation is readable can write, if is read, that can only read cannot write. Of course, if it is read-only, you can call the OpenReadAsync method directly.

The DataWriter class exposes N writexxxxx methods, which can write many underlying types, such as bytes, int, double, string, and, of course, date time.

Remember, after you finish writing the data, remember to call the Storeasync method, because writer does not write to the stream immediately, it writes the data into the buffer, waits for the Storeasync method call, writes the contents of the buffer to the stream, and cleans up the buffer.

When there is no data saved to the stream in the DataWriter buffer, the Unstoredbufferlength property returns the unsaved data size, and if Storeasync is called, the property becomes 0.

The following code demonstrates reading the time that was just saved to the file.

                //Get FileStorageFile file =awaitDocLib.                Getfileasync (filename); if(File! =NULL)                {                    //Open stream                    using(Irandomaccessstream stream =awaitfile. OpenReadAsync ()) {//Read the time                        using(DataReader dr=NewDataReader (Stream)) {                            awaitDr. LoadAsync ((UINT) stream.                            Size); DateTimeOffset DT=Dr.                            Readdatetime (); Displaystr= dt. ToString ("yyyy m month D Day HH:mm:ss"); }                    }                }            }            Catch(filenotfoundexception) {displaystr="file not found. "; }            Catch(Exception ex) {displaystr=Ex.            Message; }

After instantiating DataReader, don't rush to read because the data is still in the stream, not in the reader's buffer, so you should first call the LoadAsync method to load the content, the parameter is the number of bytes to load, and the return value is the actual size of the load. Once loaded, you are ready to read.

The third option is to mix. NET and RT library APIs to read and write. Under the System.IO namespace, two extension classes are defined.

The first is windowsruntimestorageextensions, which is an extension to the Storagefile class, for example, Call the Openstreamforwriteasync method to get a stream instance of. NET directly, so you can read and write using the idiomatic. NET approach.

The other is windowsruntimestreamextensions, which is an extension of the stream that supports the conversion of streams in. NET to streams in Rt.

Some people will ask, since there is RT API, why also let it interact with. Net. You'll find out if you think about it.

1, the UWP supports the writing language has JS, C + +, also have vb.net and C#,c# and VB are based on. NET language, so in the UWP app code you can use C # basic type, such as int,byte,double,bool,string,float, etc. It is because it is a combination of two API subsets that no. NET core can write code in these languages.

2. If some third-party libraries are using. NET core development that can be ported across platforms, then this interaction is needed to call each other.

In fact, it is not difficult to understand, like the Chinese and Western medicine can be combined with the same truth, put the brain flexible a little can not understand.

The following code demonstrates writing to a file.

StorageFile file =awaitDocLib. Createfileasync ("Some.txt", creationcollisionoption.replaceexisting); Tag=file.            Name; using(Irandomaccessstream stream =awaitfile. OpenAsync (Fileaccessmode.readwrite)) {//convert to. NET IO stream                using(StreamWriter writer =NewStreamWriter (stream. Asstreamforwrite (), System.Text.Encoding.UTF8)) {//Write Contentwriter.                Write (content); }            }

The following code shows the read-out content.

            Try{StorageFile file=awaitDoc.                Getfileasync (filename); using(Irandomaccessstream stream =awaitfile. OpenReadAsync ()) {using(StreamReader rd =NewStreamReader (stream. Asstreamforread (), System.Text.Encoding.UTF8)) {TB. Text=Rd.                    ReadToEnd (); }                }            }            Catch(FileNotFoundException) {TB. Text="file not found. "; }            Catch(Exception ex) {TB. Text=Ex.            Message; }

StreamWriter and StreamReader I'm not going to introduce you, it's a lot more fun in. Net.

All right, three kinds of programs are introduced, as to how to use, see for yourself, or that sentence-things are not fixed law.

Sample source code Download

========================================================

Next time, tell a little story.

If you ask me: Old week, your memory is not particularly good.

Really, but that was a child, do not know why, the more grow up as if the memory of the more backward. Think about the old week in elementary school, never review can test the first place, of course, the total number of 90来 people, hehe.

Even Chinese textbooks on the back of the text, ancient poetry, English textbooks on the dialogue, the old weeks do not have to back after class, directly in the classroom completed, go home after no review. Also do not know what reason, at that time really can say is the photographic memory.

After the junior high school is not very good, look at the basic can not remember, less said also to see two to three times, especially the back of classical Chinese. Anyway, always feel old, memory decline. As a child can not forget the ability of all, now take a piece of Tang poetry out, I must at least read n times, copy on M back to back down, basically lost the kind of childhood that can look back down the ability.

Alas, want to years is really a scalpel, the memory is a knife and a knife to cut away.

Three ways to read and write the "Win 10 application Development" file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.