Windows phone 8 Study Notes (2) Data File Operations

Source: Internet
Author: User
Document directory
  • 1) installation folder
  • 2) Local folder (WP7: Independent bucket)
  • 3) Media Library
  • 4) SD card
  • 1) read the content of the resource file AppResources. resx.
  • 2) read the compiled resource file
  • 3) access the installation folder
  • 1) operate files in local folders
  • 2) access key-value pairs
  • 3) installation folder, local folder path access method

Windows phone 8 applications are only used to access data file storage in four locations: installation folder, local folder (independent storage space), media library, and SD card. This section describes their usage and restrictions. The usage of the local database is also included.

Quick Navigation:
I. Analysis of various data file storage methods
Ii. Install folders
3. Local folder (independent bucket)
Iv. media library operations
V. Local Database

1. Analysis of various data file storage methods 1) installation folder

The installation folder is the root folder of the disk after the application is installed. It provides read-only access permissions. It corresponds to "C: \ Data \ Programs \ {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} \ Install \" in the phone \".
Generally, the following information can be obtained at this location:
Resource file AppResources. resxResource files are generally used to define strings and international resources. They can also be compiled to store images.
Compiled resource file
Other files in the installation directory

Features: Read-only, allowing you to access application-related resources and files.

2) Local folder (WP7: Independent bucket)

Windows phone 8 assigns a local folder to each application. Generally, you can only access your local folder and have full read and write permissions on your local folder. The path in the phone is generally: "C: \ Data \ Users \ DefApps \ AppData \ {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} \ Local"
Main features of local folders:
Free read/write storage files
Store Local databases
Access key-value pairs

Features: read/write operations are not limited. They are mainly used to process application-related files.

3) Media Library

A media repository is the only shared access area that allows you to access images, videos, and music. The image library address is: "C: \ Data \ Users \ Public \ Pictures \"
Main features of the media Repository:
Provides shared media file access and partial read/write permissions.
Features: Read-only, write permission restriction, and strong sharing.

4) SD card

The SD card is associated with the following chapter. You can visit the Startup File Association of the Windows phone 8 learning Notes application and SD card access to learn in advance. If the connection does not take effect, please wait for the release.

Ii. Install the folder 1) read the content of AppResources. resx in the resource file.

Create a WP8 project, add a new item, resource file, and "Resource1.resx ". Add a string resource named "String1" and set it to "Test ".

Switch to image resources, and upload the image into resourceimg.png"

Then, we 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 #]

// Obtain the character resource string myString1 = Resource1.String1; // obtain the Image 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 image to the Resource mode. Generally, the image file generation operation in a project is set to "content". Here we set it to "Resource ". Add an Image to Image/2.png, right-click the property, and set the generate operation to "Resource ". At this time, we cannot access images through direct paths. Let's look at how to obtain images in XAML and 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 StreamResourceInfo streamResourceInfo = Application in the installation folder. 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 in the installation directory through code.

[C #]

// Obtain the installation folder StorageFolder installedLocation = Package. current. installedLocation; // obtain the subfolder set var folders = await installedLocation in the installation folder. getFoldersAsync (); var folderNames = folders. select (x => x. name ). toArray (); // obtain the file set var files = await installedLocation in the installation folder. getFilesAsync (); var fileNames = files. select (x => x. path ). toArray ();

In addition, you can access the installation folder through the path. The following operations will access the image file and display it to the image 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);

 

3. Local folders (independent buckets) 1) operate files in local folders

WP7:
[C #]

// Using (IsolatedStorageFile storageFile = IsolatedStorageFile) method for accessing an independent bucket (local folder) in WP7. getUserStoreForApplication () {// get all file name sets in the local folder var fileNames = storageFile. getFileNames (); // operation file var storageFileStrem = storageFile. openFile ("test.txt", FileMode. openOrCreate );}

WP8:
[C #]

// Method for accessing local folders (independent buckets) in WP8 // obtain the 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 after the application exits. The following is how to use it:

[C #]

// Store the key value pair IsolatedStorageSettings. applicationSettings. add ("Key1", "value1"); isolatedstorageset.pdf. applicationSettings. save (); // obtain the key-Value Pair MessageBox. show (IsolatedStorageSettings. applicationSettings ["Key1"]. toString ());
3) installation folder, local folder path access method

For file operations accessed by path, the URL prefix varies depending on the location and API. Sort the related URL prefixes as follows:

  Windows namespace Other APIs
Installation Folder Ms-appx :/// Appdata :/
Local folder Ms-appdata :/// Isostore :/

 

Iv. media library operations

List the basic operations of the media repository and the photo read/write API:

[C #]

MediaLibrary mediaLibrary = new MediaLibrary (); string path = string. empty; if (mediaLibrary. pictures. count> 0) // obtain the absolute path of the media image library. path = Microsoft. xna. framework. media. phoneExtensions. mediaLibraryExtensions. getPath (mediaLibrary. pictures [0]); // obtain all the photos in the media library var Pictures = mediaLibrary. pictures; // Save the thumbnail of the first image in the Image Library to the saved image folder mediaLibrary. savePicture ("myImg.jpg", Pictures [0]. getThumbnail (); // obtain the folder set var ImgFolerNames = mediaLibrary in the photo library and directory. rootPictureAlbum. albums. select (x => x. name ). toArray ();

 

V. Local Database

In Windows phone 8, you can manage data in a way similar to sqlserver, which is a local database. Local databases are stored in the form of files. Generally, they can be stored in two locations, including the installation folder and local folder. Because the installation folder is read-only, if you do not need to manipulate the data, you can place it in this location. If you need to access the data, we can place it in a local folder. This example creates a database that contains a student table and supports addition, deletion, modification, and query of the student table.

First, we need to create a DataContext:

[C #]

Public class MyDataContext: DataContext {// defines the connection string public static string DBConnectionString = "Data Source = isostore:/MyDb. sdf "; public MyDataContext (): base (DBConnectionString) {}// <summary> // Student Table /// </summary> public Table <Student> Students ;}

Create a student data table:

[C #]

[Table] public class Student: INotifyPropertyChanged, INotifyPropertyChanging {// define ID, primary key field, private int _ id required; /// <summary> /// No. /// </summary> [Column (IsPrimaryKey = true, IsDbGenerated = true, DbType = "int not null Identity ", canBeNull = false, AutoSync = AutoSync. onInsert)] public int Id {get {return _ id;} set {if (_ id! = Value) {policypropertychanging ("Id"); _ id = value; policypropertychanged ("Id") ;}} private string _ name; /// <summary> // Student Name // </summary> [Column] public string name {get {return _ name;} set {if (_ Name! = Value) {policypropertychanging ("Name"); _ name = value; policypropertychanged ("Name") ;}} private int _ age; /// <summary> // Age // </summary> [Column] public int age {get {return _ age;} set {if (_ Age! = Value) {policypropertychanging ("Age"); _ age = value; policypropertychanged ("Age") ;}}# region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; // Used to modify y the page that a data context property changed private void policypropertychanged (string propertyName) {if (PropertyChanged! = Null) {PropertyChanged (this, new PropertyChangedEventArgs (propertyName) ;}# endregion # region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; // Used to modify y the data context that a data context property is about to change private void policypropertychanging (string propertyName) {if (PropertyChanging! = Null) {PropertyChanging (this, new PropertyChangingEventArgs (propertyName) ;}# endregion}

Here is the logic for operating 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 a database if (! Db. databaseExists () db. createDatabase (); // Add Student student1 = new Student {Id = 1, Name = "James", Age = 15}; db. students. insertOnSubmit (student1); List <Student> students = new List <Student> (); students. add (new Student {Id = 2, Name = "", Age = 16}); students. add (new Student {Id = 3, Name = "", Age = 17}); db. students. insertAllOnSubmit (students); db. submitChanges ();} private void Show () {MyDataContext db = new MyDataContext (); // display listbox1.ItemsSource = db for students older than 15 years old. students. where (x => x. age> 15);} private void Delete () {MyDataContext db = new MyDataContext (); // Delete the student var query = db whose name is Li Si. students. where (x => x. name = "Li Si"); db. students. deleteAllOnSubmit (query); db. submitChanges ();} private void Update () {MyDataContext db = new MyDataContext (); // Add all students plus one year old foreach (var student in db. students) {student. age ++;} db. submitChanges ();}

 

By Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan)
Copyright: The copyright of this article is shared by the author and the blog. The detailed link of this article must be noted during reprinting; otherwise, the author will be held legally liable. Previous Article: Windows phone 8 learning notes touch Input
Series directory
Next article: learning notes communication for Windows phone 8
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.