Windows phone 8 學習筆記(2) 數據文件操作


Windows phone 8 應用用於數據文件存儲訪問的位置僅僅限於安裝文件夾、本地文件夾(獨立存儲空間)、媒體庫和SD卡四個地方。本節主要講解它們的用法以及相關限制性。另外包括本地數據庫的使用方式。

快速導航:
    一、分析各類數據文件存儲方式
    二、安裝文件夾
    三、本地文件夾(獨立存儲空間)
    四、媒體庫操作
    五、本地數據庫

一、分析各類數據文件存儲方式

1)安裝文件夾

安裝文件夾即應用安裝以后的磁盤根文件夾,它提供只讀的訪問權限。它在手機中對應的路徑為“ C:\Data\Programs\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\Install\”。
    一般在這個位置可以拿到如下信息:
    資源文件AppResources.resx  資源文件一般用於定義字符串,國際化資源等,也可以編譯存放圖片
    被編譯的資源文件 
    安裝目錄的其他文件 
    特點:只讀,可以訪問與應用程序相關的資源與文件。

2)本地文件夾(WP7:獨立存儲空間)

  Windows phone 8 為每個應用分配了一個本地文件夾,一般情況下只能訪問自己的本地文件夾,對自己的本地文件夾具備完全的讀寫權限。它在手機中的路徑一般為:“C:\Data\Users\DefApps\AppData\{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\Local”
    本地文件夾主要功能:
    自由讀寫存儲文件 
    存放本地數據庫 
    存取鍵值對 
    特點:讀寫操作不限制,主要用於處理應用相關的文件。

3)媒體庫

   媒體庫是唯一一個共享訪問區域,可以訪問圖片、視頻、音樂等。圖片庫的地址為:“C:\Data\Users\Public\Pictures\”
    媒體庫主要功能:
    提供共享式的媒體文件訪問,部分讀寫權限 
    特點:可讀取,寫權限部分限制,共享性強。

4)SD卡

SD卡與后面的章節關聯,你可以訪問《Windows phone 8 學習筆記 應用的啟動 文件關聯以及SD卡訪問》 提前了解,如果連接未生效請耐心等待發布^_^。

  

二、安裝文件夾

1)讀取資源文件資源文件AppResources.resx的內容

新建WP8項目,添加新建項,資源文件,“Resource1.resx”。添加字符串資源,名稱為“String1”值為“Test”。


切換到圖片資源,添加圖片“ResourceImg.png”


然后,我們訪問這些資源,代碼如下:

[XAML]
        <!--ContentPanel - 在此處放置其他內容-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel x:Name="stackPanel" Grid.Row="1">
            </StackPanel>
        </Grid>
[C#]
            //獲取字符資源
            string myString1 = Resource1.String1;
            //獲取圖片資源
            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)讀取被編譯的資源文件

首先,我們設置圖片為資源模式,一般的項目中的圖片文件的生成操作設置為“內容”,這里設置為“Resource”。添加一張圖片到Image/2.png,右鍵屬性,設置生成操作為“Resource”。這個時候我們不能通過直接路徑的方式訪問圖片,我們分別看看在XAML中和代碼中如何獲取圖片。

[XAML]
<Image Source="/PhoneApp1;component/Image/2.png"></Image>
[C#]
Uri uri = new Uri("/PhoneApp1;component/Image/2.png", UriKind.Relative);
//查看安裝文件夾中的資源文件
StreamResourceInfo streamResourceInfo = Application.GetResourceStream(uri);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(streamResourceInfo.Stream);
Image image = new Image();
image.Source = bitmapImage;

3)訪問安裝文件夾

我們通過代碼獲取安裝目錄下的所有文件和文件夾。

[C#]
//獲取安裝文件夾
StorageFolder installedLocation = Package.Current.InstalledLocation;
//獲取安裝文件夾下的子文件夾集合
var folders = await installedLocation.GetFoldersAsync();
var folderNames = folders.Select(x => x.Name).ToArray();
//獲取安裝文件夾下的文件集合
var files = await installedLocation.GetFilesAsync();
var fileNames = files.Select(x => x.Path).ToArray();

另外,我們還可以通過路徑的方式訪問安裝文件夾,如下操作將訪問圖片文件,並展示到圖片控件。

[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);

 

三、本地文件夾(獨立存儲空間)

1)在本地文件夾中操作文件

    WP7:
[C#]
 //WP7中存取獨立存儲空間(本地文件夾)的方法
 using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
 {
     //獲取本地文件夾下所有的文件名集合
     var fileNames = storageFile.GetFileNames();
     //操作文件
     var storageFileStrem = storageFile.OpenFile("test.txt", FileMode.OpenOrCreate);
 }
    WP8:
[C#]
//WP8中存取本地文件夾(獨立存儲空間)的方法
//獲取本地文件夾
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
//操作文件
var file = await localFolder.GetFileAsync("test.txt");
var fileRandomAccessStream = await file.OpenAsync(FileAccessMode.Read);
var fileStream = fileRandomAccessStream.AsStream();
var path = localFolder.Path;

2)存取鍵值對

ApplicationSettings用於存儲當應用程序退出后需要保存的輕量級數據。下面是使用方法:

[C#]
//存儲鍵值對
IsolatedStorageSettings.ApplicationSettings.Add("Key1", "value1");
IsolatedStorageSettings.ApplicationSettings.Save();
//獲取之前存儲的鍵值對
MessageBox.Show(IsolatedStorageSettings.ApplicationSettings["Key1"].ToString());

3)安裝文件夾、本地文件夾的路徑訪問方式

對於使用路徑訪問的文件操作,URL前綴根據位置、API不同都有所不同。相關的URL前綴整理如下:

  Windows 命名空間 其他API
安裝文件夾 ms-appx:/// appdata:/
本地文件夾 ms-appdata:/// isostore:/

 

四、媒體庫操作

列舉下媒體庫的基本操作,以及照片讀寫操作API:

[C#]
MediaLibrary mediaLibrary = new MediaLibrary();
string path = string.Empty;
if (mediaLibrary.Pictures.Count > 0)
    //取得媒體圖片庫的絕對路徑
    path = Microsoft.Xna.Framework.Media.PhoneExtensions.MediaLibraryExtensions.GetPath(mediaLibrary.Pictures[0]);
//獲取媒體庫全部照片
var Pictures = mediaLibrary.Pictures;
//把圖片庫第一張圖片的縮略圖存到已保存的圖片文件夾
mediaLibrary.SavePicture("myImg.jpg", Pictures[0].GetThumbnail());
//獲取照片庫跟目錄下包含照片的文件夾集合
var ImgFolerNames = mediaLibrary.RootPictureAlbum.Albums.Select(x => x.Name).ToArray();

 

五、本地數據庫

在Windows phone 8 提供了類似sqlserver的方式管理數據,這就是本地數據庫,本地數據庫是文件形式存儲的,一般可以存放在兩個位置,安裝文件夾和本地文件夾。由於安裝文件夾只讀,所以如果不需要操縱數據,則可以放在這個位置,如果需要對數據進行存取,我們可以放到本地文件夾。本文示例將創建一個數據庫,包含一張學生表,並且支持對學生表進行增刪改查操作。

首先,我們需要創建一個DataContext:

[C#]
    public class MyDataContext : DataContext
    {
        //定義連接字符串
        public static string DBConnectionString = "Data Source=isostore:/MyDb.sdf";

        public MyDataContext()
            : base(DBConnectionString)
        { }

        /// <summary>
        /// 學生表
        /// </summary>
        public Table<Student> Students;
    }

創建學生數據表:

[C#]
    [Table]
    public class Student : INotifyPropertyChanged, INotifyPropertyChanging
    {
        // 定義ID,主鍵字段,必備
        private int _id;
        /// <summary>
        /// 編號
        /// </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)
                {
                    NotifyPropertyChanging("Id");
                    _id = value;
                    NotifyPropertyChanged("Id");
                }
            }
        }

        private string _name;
        /// <summary>
        /// 學生姓名
        /// </summary>
        [Column]
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                if (_name != value)
                {
                    NotifyPropertyChanging("Name");
                    _name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }

        private int _age;
        /// <summary>
        /// 年齡
        /// </summary>
        [Column]
        public int Age
        {
            get
            {
                return _age;
            }
            set
            {
                if (_age != value)
                {
                    NotifyPropertyChanging("Age");
                    _age = value;
                    NotifyPropertyChanged("Age");
                }
            }
        }


        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify the page that a data context property changed
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region INotifyPropertyChanging Members

        public event PropertyChangingEventHandler PropertyChanging;

        // Used to notify the data context that a data context property is about to change
        private void NotifyPropertyChanging(string propertyName)
        {
            if (PropertyChanging != null)
            {
                PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
            }
        }

        #endregion
    }

這里是對學生表進行操作的邏輯:

[XAML]
<ListBox x:Name="listbox1">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
[C#]
 private void Add()
 {
     MyDataContext db = new MyDataContext();
     //創建數據庫
     if (!db.DatabaseExists())
         db.CreateDatabase();

     //添加學生
     Student student1 = new Student
     {
         Id = 1,
         Name = "張三",
         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();
     //顯示年齡大於15歲的學生
      listbox1.ItemsSource = db.Students.Where(x => x.Age > 15);
 }

 private void Delete()
 {
     MyDataContext db = new MyDataContext();
     //刪除姓名為李四的學生
     var query = db.Students.Where(x => x.Name == "李四");
     db.Students.DeleteAllOnSubmit(query);
     db.SubmitChanges();
 }

 private void Update()
 {
     MyDataContext db = new MyDataContext();
     //將所有的學生年齡加一歲
     foreach (var student in db.Students)
     {
         student.Age++;
     }
     db.SubmitChanges();
 }

 

作者:李盼(Lipan)
出處: [Lipan]http://www.cnblogs.com/lipan/
版權聲明:本文的版權歸作者與博客園共有。轉載時須注明本文的詳細鏈接,否則作者將保留追究其法律責任。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM