Win8Metro中,我們不能在向以前那樣調(diào)用WIN32的API函數(shù)來進行文件操作,因此,下面就來介紹一下Win8 Metro中文件的讀寫操作。
1 Windows 8 Metro Style App中文件的操作都包含在Windows.Storage命名空間中,其中包括StorageFolder,StorageFile,FileIO等類庫。
2 Win8文件的讀寫操作都是異步方式進行的,因此要使用async
3 創(chuàng)建文件:
StorageFile storageFile=await
Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption.ReplaceExisting);
這里我們創(chuàng)建了一個1.txt的文檔,如果已經(jīng)存在這個文檔,那么新建的文檔將替換,覆蓋掉舊文檔。
由于文檔讀寫是異步方式操作,因此,我們要將它放到async修飾的函數(shù)里才可以使用,具體如下:
private async void SelectImageOne(byte[]outArary)
{
StorageFile storageFile=await Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(storageFile, outArary);
}
在上述的代碼中,參數(shù)是我們要寫入到文件“1.txt”里的內(nèi)容,這里是一個byte[]數(shù)組。
4 寫入文件:
如3中的代碼所示await FileIO.WriteBytesAsync(storageFile, outArary);
寫入文件的方法是FileIO中的write方法,這里一共有以下四種方法:
WriteBufferAsync(Windows.Storage.IStorageFile file, IBuffer buffer);
WriteBytesAsync(Windows.Storage.IStorageFile file, byte[] buffer);
WriteLinesAsync(Windows.Storage.IStorageFile file, IEnumerable<string> lines);
WriteLinesAsync(Windows.Storage.IStorageFile file, IEnumerable<string> lines,
UnicodeEncoding encoding);
WriteTextAsync(Windows.Storage.IStorageFile file, string contents);
WriteTextAsync(Windows.Storage.IStorageFile file, string contents,
UnicodeEncoding encoding);
這里我們列舉的是寫入byte[]的方法。
5 打開文件:
StorageFile storageFile=await
Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption. OpenIfExists);
這里我們打開了一個名字為”1.txt”的文本文件。
6 讀取文件:
在FileIO中有三種文件讀取方法,分別讀取不同的文件:
await FileIO.ReadTextAsync(Windows.Storage.IStorageFile file);
await FileIO.ReadTextAsync(Windows.Storage.IStorageFile file, UnicodeEncoding encoding);//返回指定的文本編碼格式
await FileIO. ReadBufferAsync (Windows.Storage.IStorageFile file);
await FileIO. ReadLinesAsync (Windows.Storage.IStorageFile file);
await FileIO. ReadLinesAsync (Windows.Storage.IStorageFile file, UnicodeEncoding encoding);
這里我們以文本為例:
string fileIContent = await FileIO. ReadTextAsync (storageFile);
這樣我們就返回了一個string文本。
我們也可以通過流來讀取文件:
IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);
using (DataReader dataReader = DataReader.FromBuffer(buffer))
{
string fileContent = dataReader.ReadString (buffer.Length);
}
7 IBuffer, byte[], Stream之間的相互轉(zhuǎn)換:
StorageFile storageFile=await
Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption. OpenIfExists);
IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);
byte[] bytes=WindowsRuntimeBufferExtensions.ToArray(buffer,0,(int)buffer.Length);
Stream stream = WindowsRuntimeBufferExtensions.AsStream(buffer);
另外一個實例:
1.首先創(chuàng)建一個文件夾,在文件夾里創(chuàng)建文件
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
string name=FileName.Text; //創(chuàng)建文件的名稱
folder =ApplicationData.Current.LocalFolder;
StorageFolder tempFolder = await folder.CreateFolderAsync("Config",CreationCollisionOption.OpenIfExists);
file =await tempFolder.CreateFileAsync(name,CreationCollisionOption.OpenIfExists);
}
2.在創(chuàng)建好的文件里,寫入我們的數(shù)據(jù),這里介紹三種寫入文件的方式
private async void WriteButton_Click(object sender, RoutedEventArgs e)
{
string content = InputTextBox.Text.Trim();
ComboBoxItem item = WriteType.SelectedItem asComboBoxItem; //選擇寫入的方式
string type = item.Tag.ToString();
switch (type)
{
case"1": //以文本的方式寫入文件
await FileIO.WriteTextAsync(file,content);
break;
case"2": //以bytes的方式寫入文件
Encoding encoding = Encoding.UTF8;
byte[] bytes = encoding.GetBytes(content);
await FileIO.WriteBytesAsync(file,bytes);
break;
case"3": //以流的方式寫入文件
IBuffer buffer = Convert(content); //將string轉(zhuǎn)換成IBuffer類型的
await FileIO.WriteBufferAsync(file,buffer);
break;
}
}
3.讀取剛才寫入文件里的數(shù)據(jù),這里也介紹三種讀取文件的方式
private async void ReadButton_Click(object sender, RoutedEventArgs e)
{
ComboBoxItem item = ReadType.SelectedItem asComboBoxItem;
string type = item.Tag.ToString();
string content = string.Empty;
switch (type)
{
case"1": //以文本的方式讀取文件
content =await FileIO.ReadTextAsync(file);
break;
case"2": //以流的方式讀取文件
IBuffer buffer = await FileIO.ReadBufferAsync(file);
content = Convert(buffer);
break;
case"3":
content =await Convert();
break;
}
ShowTextBox.Text = content;
}
private IBuffer Convert(string text) //將string轉(zhuǎn)換成IBuffer類型的
{
using (InMemoryRandomAccessStream stream = newInMemoryRandomAccessStream())
{
using (DataWriter dataWriter = newDataWriter())
{
dataWriter.Writestring(text);
return dataWriter.DetachBuffer();
}
}
}
private string Convert(IBuffer buffer) //將IBuffer轉(zhuǎn)換成string類型的
{
string text = string.Empty;
using (DataReader dataReader=DataReader.FromBuffer(buffer))
{
text = dataReader.ReadString(buffer.Length);
}
return text;
}
private async Task<string> Convert()
{
string text=string.Empty;
using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
{
using (DataReader dataReader = newDataReader(readStream))
{
UInt64 size = readStream.Size;
if (size <= UInt32.MaxValue)
{
UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
text = dataReader.ReadString(numBytesLoaded);
}
}
}
return text;
}
4.讀取文件的屬性
private async void ReadPropertyButton_Click(object sender, RoutedEventArgs e)
{
ComboBoxItem item = Files.SelectedItem asComboBoxItem;
string name = item.Content.ToString();
StorageFolder tempFolder =await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("Config");
if (tempFolder != null)
{
file =await tempFolder.GetFileAsync(name);
if (file != null)
{
StringBuilder builder = newStringBuilder();
builder.AppendLine("文件名稱:"+file.Name);
builder.AppendLine("文件類型:"+file.FileType);
BasicProperties basic = await file.GetBasicPropertiesAsync();
builder.AppendLine("文件大小:"+basic.Size+"bytes");
builder.AppendLine("上次修改時間:"+basic.DateModified);
builder.AppendLine("文件路徑:"+file.Path);
List<string> list = newList<string>();
list.Add("System.DateAccessed");
list.Add("System.FileOwner");
IDictionary<string, object> extra = await file.Properties.RetrievePropertiesAsync(list);
var property = extra["System.DateAccessed"];
if (property != null)
{
builder.AppendLine("文件創(chuàng)建時間:"+property);
}
property = extra["System.FileOwner"];
if(property!=null)
{
builder.AppendLine("文件所有者:"+property);
}
DisplyProperty.Text = builder.ToString();
}
}
}
5.復制刪除文件
private async void OKButton_Click(object sender, RoutedEventArgs e)
{
try
{
ComboBoxItem item=FilesList.SelectedItem asComboBoxItem;
string fileName = item.Content.ToString(); //獲得選中的文件名稱
int index=fileName.IndexOf('.');
string firstName = fileName.Substring(0,index);
string type = fileName.Substring(index);
StorageFolder tempFolder = await folder.GetFolderAsync("Config"); //文件在Config文件夾下放置著
file =await tempFolder.GetFileAsync(fileName);
if (file == null)
{
Msg.Text ="文件不存在!";
return;
}
if (CopyoButton.IsChecked.Value) //判斷進行復制還是刪除
{
StorageFile copy = await file.CopyAsync(tempFolder,firstName+"復制"+type,NameCollisionOption.ReplaceExisting);
Msg.Text ="復制成功!!";
}
else
{
await file.DeleteAsync();
Msg.Text ="刪除成功。。";
}
}
catch
{
Msg.Text ="操作失。";
}
}