Development of New Fashion Windows 8 (39): File Read and Write

Source: Internet
Author: User
Tags tmd file

File Reading and Writing should not be unfamiliar to us, but should be said to be very familiar. When learning other development technologies of. net, I/O must be learned. After all, it is the most basic operation for data storage and processing.

In Windows Store application development, you also need to read and write files. However, due to security and permission restrictions, we cannot "work freely" as before. This is advantageous. We need to know that the "board and brick" application is for mobile platforms, at least normally. If we want to read and write various paths as we used to, consider using traditional desktop applications.

In fact, what is Windows 8 Application Development? It does not only contain store applications. As long as the programs that can run on Windows 8 can be said to be Windows 8 applications, like the old-fashioned MFC, previous Windows Forms and later WPF can be integrated into Windows 8 applications.

In store applications, there are usually two types of directories we want to read and write. One is the application data folder, and the other is the user's document library. As for the path, if you think ms-appx: // and MS-appdata: // are not easy to remember, even if you do not know the path representation, it will not affect your program writing. Believe it or not, I believe it.

Now let's take the first example of the text to see how to use the existing API to access the local data directory of the application.

Step 1: Create a new "Panel tile" application project. I don't need to talk about this. 38 words are omitted here.

Step 2: layout. The XAML of mainpage. XAML is as follows:

<Page X: class = "app1.mainpage" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns: Local = "using: app1" xmlns: D = "http://schemas.microsoft.com/expression/blend/2008" xmlns: MC = "http://schemas.openxmlformats.org/markup-compatibility/2006" MC: ignorable = "D"> <grid background = "{staticresource applicationpagebackgroundthemebrush}"> <richtextblock margin = "15"> <Paragraph fontsize = "24"> <span> local storage directory: </span> <run X: Name = "rnlocal"/> <linebreak/> <span> roaming storage directory: </span> <run X: name = "rnroaming"/> <linebreak/> <span> temporary directory: </span> <run X: name = "rntemp"/> </Paragraph> </richtextblock> </GRID> </Page>

Step 3: Write C # code. Despite rumors, I still like C # very much. After all, rumors start with fools and end with wise men.

        protected override void OnNavigatedTo(NavigationEventArgs e)        {            this.rnLocal.Text = Windows.Storage.ApplicationData.Current.LocalFolder.Path;            this.rnRoaming.Text = Windows.Storage.ApplicationData.Current.RoamingFolder.Path;            this.rnTemp.Text = Windows.Storage.ApplicationData.Current.TemporaryFolder.Path;        }

In fact, you can see from the code above why I mentioned earlier that even if you do not remember the path architecture method, you can easily access these folders.

Run it.

 

We can see from the running results that these directories are located under user \ appdata \ Local \ application package name.

 

 

Next we will use the second example to read and write files to the local data storage area.

This is quite flexible. The simplest method is to implement two classes: fileio and pathio.

All are static classes, and the call method is complete. Here we select the fileio class to do the experiment.

Step 1: Create a store application project.

Step 2: The XAML on the home page is as follows:

<Grid background = "{staticresource applicationpagebackgroundthemebrush}"> <grid. rowdefinitions> <rowdefinition Height = "*"/> <rowdefinition Height = "Auto"/> <rowdefinition Height = "*"/> </grid. rowdefinitions> <textbox X: Name = "txtinput" margin = "13" grid. row = "0" textwrapping = "Wrap"/> <stackpanel orientation = "horizontal" margin = "14,10" grid. row = "1"> <button fontfamily = "segoe UI symbol" fontsize = "25" Click = "onwrite"> <button. content> <grid. columndefinitions> <columndefinition width = "Auto"/> <columndefinition width = "*"/> </grid. columndefinitions> <textblock X: Name = "tbsob" grid. column = "0" text = ""/> <textblock grid. column = "1" text = "Write File"/> </GRID> </button. content> </button> <button margin = "16, 0, 0, 0" fontfamily = "segoe UI symbol" fontsize = "25" Click = "onread"> <button. content> <grid. columndefinitions> <columndefinition width = "*"/> <columndefinition width = "Auto"/> </grid. columndefinitions> <textblock grid. column = "0" text = "read from file"/> <textblock grid. column = "1" text = "{binding elementname = tbsob, Path = text}" rendertransformorigin = "0.5, 0.5"> <textblock. rendertransform> <rotatetransform angle = "180" type = "codeph" text = "/codeph"/> </textblock. rendertransform> </textblock> </GRID> </button. content> </button> </stackpanel> <textblock X: Name = "txtread" grid. row = "2" margin = "15" textwrapping = "Wrap" fontsize = "24"/> </GRID>

Step 3: write the code.

Private async void onwrite (Object sender, routedeventargs e) {If (string.isnullorwhitespace(this.txt input. text) return; var local = windows. storage. applicationdata. current. localfolder; var myfile = await local. createfileasync ("my.txt"); If (myfile! = NULL) {await windows. storage. fileio. writetextasync (myfile, this.txt input. text); windows. UI. popups. messagedialog DLG = new windows. UI. popups. messagedialog ("written successfully. "); Await DLG. showasync () ;}} private async void onread (Object sender, routedeventargs e) {windows. UI. popups. messagedialog DLG = NULL; string MSG = string. empty; try {var local = windows. storage. applicationdata. current. localfolder; var file = await local. getfileasync ("my.txt"); If (file! = NULL) {this.txt read. Text = await windows. Storage. fileio. readtextasync (File); MSG = "read complete. ";}} Catch (exception ex) {MSG = ex. Message;} DLG = new windows. UI. popups. messagedialog (MSG); await DLG. showasync ();}

Shows the running result.

 

Next we will show the second sword-knownfolders class, using its static members, we can obtain the path of user's personal directories, such as "my images", "My music", and "My Documents". In this way, we can also read and write files. These guys are shown in the content.

I don't need to explain it one by one. I can understand what it means in the fifth-grade English.

 

The third example in this article is as follows: Write the file to the document library.

Step 1: Create a store application.

Step 2: The homepage layout is relatively simple, there is no way, and life is difficult.

<Grid background = "{staticresource applicationpagebackgroundthemebrush}"> <stackpanel margin = "20"> <textbox X: name = "txtinput" textwrapping = "Wrap" Height = "320" fontsize = "20"/> <button content = "Save to document library" margin =, 0, 0 "padding =" 12, 7 "fontsize =" 25 "Click =" onsavedoc "/> </stackpanel> </GRID>

Step 3: Write the background code and write the content in the text box to the document library.

Private async void onsavedoc (Object sender, routedeventargs e) {If (string.isnullorwhitespace(this.txt input. text) return; var mydocuments = windows. storage. knownfolders. documentslibrary; // create the file var tmdfile = await mydocuments. createfileasync ("data. TMD "); If (tmdfile! = NULL) {string strinfo = string. Empty; try {await windows. Storage. fileio. writetextasync (tmdfile, this.txt input. Text); strinfo = "written to the document. ";} Catch (exception ex) {strinfo = ex. message;} // The operation result is displayed in windows. UI. popups. messagedialog DLG = new windows. UI. popups. messagedialog (strinfo); await DLG. showasync ();}}

Step 4: The user's personal documents are not as easy as writing to the application data storage area. After all, you need to consider security issues. Therefore, open the inventory file designer, switch to the "functions" tab and select "document library ".

At this time, we can see that the tag shows a Red Cross, because for security reasons, although the document library is accessible, it does not mean that you can do whatever you want, you must specify the file type, your code can only operate on the specified file type, but cannot operate on other unspecified files.

Switch to the "Declaration" tab, select "file type association" from the drop-down list, click "add", and then proceed on the right side of the pane. Our file class is a TMD file.

 

Now you can try to run the program.

 

After the operation is successful, open "My documents", find the data. TMD file, and open it in notepad to check whether there is any content in it.

If you see the saved content, the experiment is successful.

The sample code will be uploaded to [Resource] Later.

 

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.