Windows Store Development Summary-file operations

Source: Internet
Author: User

1. Read isolated Storage

Each Metro program has three folders: Local,roaming,temp. Access methods are the same for each folder.

    • Local is used to store the data locally, which is a program-specific folder.
    • Roaming stored files may be used to synchronize with other programs.
    • The files in temp can be erased every time the program is started.

The following code is how to use them:

 Public Async voidIsolatedStorage () {//Settings    var_name = \ \"myFileName"; var_folder =Windows.Storage.ApplicationData.Current.LocalFolder; var_option =Windows.Storage.CreationCollisionOption.ReplaceExisting; //Create File    var_file =await_folder.createfileasync (_name, _option); //Write Content    var_writethis = \ \"Hello world!\\"; awaitWindows.Storage.FileIO.WriteTextAsync (_file, _writethis); //Acquire file_file =await_folder.getfileasync (_name); //Read Content    var_readthis =awaitWindows.Storage.FileIO.ReadTextAsync (_file);}
1.1. Create a file in a folder
first create a folder, create a file in the folderPrivate Async voidCreatebutton_click (Objectsender, RoutedEventArgs e) {stringName=filename.text;//name of the created filefolder=ApplicationData.Current.LocalFolder; Storagefolder TempFolder=awaitFolder. Createfolderasync ("Config", creationcollisionoption.openifexists); File=awaitTempfolder.createfileasync (name,creationcollisionoption.openifexists); }
1.2 Writing data to a created file
Here are three ways to write filesPrivate Async voidWritebutton_click (Objectsender, RoutedEventArgs e) {stringContent =InputTextBox.Text.Trim (); ComboBoxItem Item= Writetype.selecteditem Ascomboboxitem;//Choose how to write       stringType =item.           Tag.tostring (); Switch(type) { Case"1"://writing to a file as text          awaitFileio.writetextasync (file,content);  Break;  Case"2"://write a file in a bytes wayEncoding Encoding=Encoding.UTF8; byte[] bytes =encoding.                            GetBytes (content); awaitFileio.writebytesasync (file,bytes);  Break;  Case"3"://write a file as a streamIBuffer Buffer= Convert (content);//converts a string into a ibuffer type                awaitFileio.writebufferasync (File,buffer);  Break; }        }
1.3 reading data from a file
 Case " 1 ": // Read file  as Text =await  fileio.readtextasync (file);
 Break ;  Case " 2 ": // stream to read files  await  fileio.readbufferasync (file);  Break ;  Case " 3 " : =
break;
1.4 String and Ibuffer and byte[] and stream convert each other
PrivateIBuffer Convert (stringText//converts a string into a ibuffer type   {             using(Inmemoryrandomaccessstream stream =NewInmemoryrandomaccessstream ()) {using(DataWriter DataWriter =Newdatawriter ())                                                  {datawriter.writestring (text); returnDatawriter.detachbuffer (); }                             } }Private stringConvert (IBuffer buffer)//converts a ibuffer into a string of type{stringText =string.   Empty; using(DataReader datareader=datareader.frombuffer (buffer)) {Text=datareader.readstring (buffer.           Length); }returntext; }Private Asynctask<string> Convert ()//load a string from a file{stringtext=string.    Empty; using(Irandomaccessstream Readstream =awaitfile. OpenAsync (Fileaccessmode.read)) {using(DataReader DataReader =Newdatareader (Readstream)) {UInt64 size=readstream.size; if(Size <=uint32.maxvalue) {UInt32 numbytesloaded=awaitDatareader.loadasync ((UInt32) size); Text=datareader.readstring (numbytesloaded); }}}returntext; }

IBuffer buffer = await fileio.readbufferasync (storageFile);

Byte[] Bytes=windowsruntimebufferextensions.toarray (buffer,0, (int) buffer. Length);

Stream stream = windowsruntimebufferextensions.asstream (buffer); 2. reading files in a project

If you want to read a resource file from your project, this file is mostly sample data or settings. It could be an XML file, a JSON file, or another format. Can I read it?

Note: Files in the project are not writable. To write to a file in a project, you need to copy it to isolated storage, or somewhere else, and then write.

The first step is to add files to the project. Note: This is your file and you need to process the file type. For example, I added a MyFile.txt file to the MyFolder directory.

Step Two

Modify the file's build action to be content. and modify the copy to output directory to always replicate. This will ensure that the file is in the program. If you do not, you cannot read the file.

Step Three

Read the file contents, the code is as follows:

Private Async voidProjectFile () {//Settings    var_path = @"MyFolderMyFile.txt"; var_folder =Windows.ApplicationModel.Package.Current.InstalledLocation; //Acquire file    var_file =await_folder.getfileasync (_path); //Read Content    var_readthis =awaitWindows.Storage.FileIO.ReadTextAsync (_file);}
3. To read a local file from a file picker (picker)


Do you want to read the file from the document library? Then use the file picker to let the user select the file.

You only need to do this:

In order to use the file picker, there is no need to do anything special. Do not make any changes to appxmanifest (reason: Using the file picker is to let the user make a choice, only the user can select the file). Therefore the picker is a statement and consent to its own ability.

The following code is used:

Async void Localfilefrompicker () {    //  Initialize file selector
   var  _picker = new   Fileopenpicker {ViewMode  = Pickerviewmode.list, suggestedstartlocation  =    Pickerlocationid.documentslibrary,}; _picker.filetypefilter.add (". txt");//Add Select what type of file    //  start file selector  
   var  _file = await   _picker.picksinglefileasync ();  if  (_file = = null   await  new  Windows. Ui. Popups.messagedialog ( " no file   " ).        Showasync ();     return  ;  //  Read file properties  
   var  _message = string . Format (\\ " file Date: {0}\\  "   await   _file.getbasicpropertiesasync ()).    DateModified);  await  new   Windows.UI.Popups.MessageDialog (_message).    Showasync ();  //  Read Select File contents  
    var await Windows.Storage.FileIO.ReadTextAsync (_file);     await New Windows.UI.Popups.MessageDialog (_content). Showasync ();}

In the above code, a fileopenpicker is initialized first. Then call the Picksinglefileasync () method of the picker to get a storagefile. Then use Messagedialog to display some details.

4. do not read local files through the file Picker (picker)


If you do not want to read the file through the file picker, can you do it? The answer is yes. But a little bit more complicated, because the program's appxmanifest file needs to be modified to request access to the document library.

Such as

Check the document library access. That's what you might notice. The function tab header has a red x. This indicates an error. How to modify it.

Need to modify the file type in the Declaration tab

Note that the file type setting cannot be *. *

such as (I only access TXT file here, so only add. txt)

Now, you can read the contents of the file

The following code I created a HelloWorld.txt file and read and write. Finally, I delete the file

Async voidLocalfilewithoutpicker () {var_name ="HelloWorld.txt"; var_folder =knownfolders.documentslibrary; var_option =Windows.Storage.CreationCollisionOption.ReplaceExisting; //Create File    var_file =await_folder.createfileasync (_name, _option); //Write Content    var_writethis ="Hello world!"; awaitWindows.Storage.FileIO.WriteTextAsync (_file, _writethis); //Acquire file    Try{_file =await_folder.getfileasync (_name);} Catch(FileNotFoundException) {/*TODO*/ }    //Read Content    var_content =awaitFileio.readtextasync (_file); await NewWindows.UI.Popups.MessageDialog (_content).    Showasync (); await_file.deleteasync ();}

The code for the polygon works well, because I declared in the Appxmanifest file the ability to read the TXT file from the document library folder.

If you request the following features in manifest: documents, pictures, music, videos, etc., you can cite these files in the library. It is important to note that returning files in a folder will be automatically filtered according to the file type declared in manifest.

Windows Store Development Summary-file operations

Related Article

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.