Windows Phone 8 Learning Note (2) data file operations

Source: Internet
Author: User

The location of Windows phone 8 apps for data file storage access is limited to four places in the installation folder, local folder (Isolated storage space), Media Library, and SD card. This section focuses on their usage and related limitations. Also includes how the local database is used.

Quick navigation:
First, analysis of various types of data file storage methods
Second, installation folder
Three, local folder (Independent storage space)
Iv. Media Library Operations
Five, local database one, analysis of various types of data file storage 1) installation folder

The installation folder is the root folder of the disk after the installation, which provides read-only access. Its corresponding path in the phone is "c:\data\programs\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\install\".
Generally in this position can get the following information:
Resource Files Appresources.resx resource files are typically used to define strings, internationalized resources, etc., and can also be compiled to store pictures
The compiled resource file
Additional files for the installation directory
Features: Read-only, access to application-related resources and files. 2) Local folder (WP7: Isolated storage space)

Windows Phone 8 assigns a local folder to each app, and generally only accesses its own local folder, with full read and write access to its own local folder. Its path in the phone is generally: "C:\data\users\defapps\appdata\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\local"
Local Folder main Features:
Free read and write storage files
Store Local Database
Access key-value pairs
Features: Read and write operations are not limited, mainly for processing application-related files. 3) Media Library

The Media Library is the only shared access area where you can access pictures, videos, music, and more. The address of the picture library is: "C:\Data\Users\Public\Pictures\"
Media Library Main Features:
Provides shared media file access, partial read and write access
Features: can read, write permission part of the limit, sharing strong. 4) SD Card

The SD card is associated with the following chapters, and you can access the startup file associations of the Windows Phone 8 learning Notes app as well as the SD card access in advance to understand that if the connection does not take effect please be patient and wait for the release of ^_^. Ii. installation folder 1) Read the contents of the resource file resource file Appresources.resx

New WP8 project, add New item, resource file, "Resource1.resx". Add a string resource named "String1" with the value "Test".

Switch to Picture resource, add Picture "Resourceimg.png"

We then access these resources with the following code:

[XAML]

        <!--Contentpanel-place other content here--        <grid x:name= "Contentpanel" grid.row= "1" margin= "12,0,12,0" >            <stackpanel x:name= "StackPanel" grid.row= "1" >            </StackPanel>        </Grid>

[C #]

            Gets the character resource            string myString1 = resource1.string1;            Get picture resource            var myresourceimg = resource1.resourceimg;            Image image = new image ();            BitmapImage BitmapImage = new BitmapImage ();            Bitmapimage.setsource (new MemoryStream (myresourceimg));            Image. Source = BitmapImage;            STACKPANEL.CHILDREN.ADD (image);
2) Read the compiled resource file

First, we set the picture as the resource mode, the general project of the image file generation action set to "content", here is set to "Resource". Add a picture to Image/2.png, right-click the property, and set the build action to "Resource". At this point we can't access the images by direct path, we'll look at how to get pictures in XAML and in code.

[XAML]

<image source= "/phoneapp1;component/image/2.png" ></Image>

[C #]

Uri uri = new Uri ("/phoneapp1;component/image/2.png", urikind.relative);//View the resource file in the installation folder StreamResourceInfo StreamResourceInfo = Application.getresourcestream (URI); BitmapImage BitmapImage = new BitmapImage (); Bitmapimage.setsource (streamresourceinfo.stream); image image = New Image () ; image. Source = BitmapImage;
3) Access the installation folder

We get all the files and folders under the installation directory by code.

[C #]

Get the installation folder Storagefolder Installedlocation = package.current.installedlocation;//Gets the set of subfolders under the installation folder var folders = await Installedlocation.getfoldersasync (); var foldernames = folders. Select (x = x.name). ToArray ();//Gets the file collection under the installation folder var files = await installedlocation.getfilesasync (); var fileNames = files. Select (x = X.path). ToArray ();

In addition, we can access the installation folder by way of path, the following operation will access the picture file, and display the picture control.

[C #]

Image image = new image (); StorageFile StorageFile = await storagefile.getfilefromapplicationuriasync (new Uri ("ms-appx:///1.jpg")); var C = await Storagefile.openreadasync (); BitmapImage BitmapImage = new BitmapImage (); Bitmapimage.setsource (C.asstream ()); image. Source = Bitmapimage;this.stackpanel.children.add (image);
Three, local folder (Isolated storage space) 1) manipulate files in a local folder WP7:
[C #]
Method using (IsolatedStorageFile StorageFile = Isolatedstoragefile.getuserstoreforapplication ()) for accessing isolated storage space (local folder) in WP7 {     //Get all the file names under the local folder     var fileNames = Storagefile.getfilenames ();     Operation File     var storagefilestrem = storagefile.openfile ("test.txt", FileMode.OpenOrCreate);}

WP8:
[C #]

WP8 methods for accessing local folders (Isolated storage space)//Get local folder var Localfolder = windows.storage.applicationdata.current.localfolder;//Operation file var File = await Localfolder.getfileasync ("test.txt"); var filerandomaccessstream = await file. OpenAsync (Fileaccessmode.read); var fileStream = Filerandomaccessstream.asstream (); var path = Localfolder.path;
2) access key value pairs

ApplicationSettings is used to store lightweight data that needs to be saved when an application exits. Here's how to use it:

[C #]

Store key value pairs IsolatedStorageSettings.ApplicationSettings.Add ("Key1", "value1"); SolatedStorageSettings.ApplicationSettings.Save ();//Gets the key value stored before MessageBox.Show ( isolatedstoragesettings.applicationsettings["Key1"]. ToString ());
3) path access for installation folder and local folder

For file operations that use path access, the URL prefix differs depending on location and API. The associated URL prefixes are organized as follows:

Windows namespaces
Other APIs

installation folder
ms-appx:///
appdata:/

Local Folder
ms-appdata:///
isostore:/Four, Media Library operation

List the basic operations of the Media Library, as well as the photo read and write operations API:

[C #]

Medialibrary medialibrary = new Medialibrary (); string path = String. Empty;if (MediaLibrary.Pictures.Count > 0)    //Get the absolute path of the Media picture library path    = Microsoft.Xna.Framework.Media.PhoneExtensions.MediaLibraryExtensions.GetPath (Medialibrary.pictures[0]);// Get Media Library all photos var Pictures = medialibrary.pictures;//The thumbnail of the first picture in the picture library survival to the Saved Pictures folder medialibrary.savepicture ("Myimg.jpg", Pictures[0]. GetThumbnail ());//Get a collection of folders containing photos in photo gallery and directory var imgfolernames = mediaLibrary.RootPictureAlbum.Albums.Select (x = X.name ). ToArray ();
V. Local Database

Windows Phone 8 provides a way to manage data like SQL Server, which is the local database, which is stored as a file, and can typically be stored in two locations, the installation folder, and a local folder. Because the installation folder is read-only, if you do not need to manipulate the data, it can be placed in this location, if you need to access the data, we can put into a local folder. This example creates a database, contains a student table, and supports the increase and deletion of student tables.

First, we need to create a DataContext:

[C #]

    public class Mydatacontext:datacontext    {        //define connection string public        static string dbconnectionstring = "Data source= Isostore:/mydb.sdf ";        Public Mydatacontext ()            : Base (dbconnectionstring)        {}//<summary>//        Student Form///        </ summary> public        table<student> Students;    }

To create a student data sheet:

[C #]

    [Table] public class student:inotifypropertychanged, inotifypropertychanging {//definition ID, primary key field, required p        rivate int _id; <summary>///number//</summary> [Column (IsPrimaryKey = true, isdbgenerated = True, Db            Type = "int not NULL Identity", Canbenull = False, AutoSync = Autosync.oninsert)] public INT Id {            get {return _id; } set {if (_id! = value) {notifypropertychanging (                    "Id");                    _id = value;                Notifypropertychanged ("Id");        }}} private string _name;            <summary>///Student name///</summary> [Column] public string Name {            get {return _name;       } set {if (_name! = value) {             Notifypropertychanging ("Name");                    _name = value;                Notifypropertychanged ("Name");        }}} private int _age; <summary>///Age///</summary> [Column] public int ages {GE            t {return _age; } set {if (_age! = value) {notifypropertychanging                    ("Age");                    _age = value;                Notifypropertychanged ("Age"); }}} #region INotifyPropertyChanged members public event PropertyChangedEventHandler Prop        ertychanged; Used to notify the page, a data context property changed private void Notifypropertychanged (String Propertyn AME) {if (propertychanged! = null) {propertychanged (this, new PropertyChange Deventargs(PropertyName)); }} #endregion #region inotifypropertychanging members public event Propertychangingeventhandl        ER propertychanging; Used to notify the data context which a data context property was about to change private void Notifypropertychang ing (string propertyname) {if (propertychanging! = null) {propertychanging (th            is, new Propertychangingeventargs (PropertyName)); }} #endregion}

Here is the logic to manipulate the student table:

[XAML]

<listbox x:name= "ListBox1" >    <ListBox.ItemTemplate>        <DataTemplate>            <textblock text= "{Binding Name}"/>        </DataTemplate>    </ListBox.ItemTemplate></ListBox>

[C #]

 private void Add () {Mydatacontext db = new Mydatacontext (); Create the database if (!db. Databaseexists ()) db.     CreateDatabase ();     Add student Student Student1 = new Student {Id = 1, Name = "Zhang san", age = 15}; Db.     Students.insertonsubmit (STUDENT1);     list<student> students = new list<student> (); Students.     ADD (new Student {Id = 2, Name = "John Doe", age = 16}); Students.     ADD (new Student {Id = 3, Name = "Harry", age = 17}); Db.     Students.insertallonsubmit (Students); Db. SubmitChanges ();     } private void Show () {Mydatacontext db = new Mydatacontext (); Show students older than 15 years of age listbox1. ItemsSource = db. Students.where (x = x.age > 15);     } private void Delete () {Mydatacontext db = new Mydatacontext (); Delete the student var query = db named John Doe.     Students.where (x = X.name = = "John Doe"); Db.     Students.deleteallonsubmit (query); Db. SubmitChanges ();     private void Update () {Mydatacontext db = new Mydatacontext (); WillAll students age plus one year old foreach (Var student in db). Students) {student.     age++; } db. SubmitChanges (); }
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.