原文: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] (http://www.cnblogs.com/lipan/)
版權宣告:本文的版權歸作者與部落格園共有。轉載時須註明本文的詳細連結,否則作者將保留追究其法律責任。