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/
版权声明:本文的版权归作者与博客园共有。转载时须注明本文的详细链接,否则作者将保留追究其法律责任。
posted @ 2013-05-31 09:18  lipan  阅读(9129)  评论(12编辑  收藏  举报