每一個Metro程序都有三個文件夾:Local,Roaming,Temp。每一個文件夾的訪問方法都是相同的.windows
下面的代碼是如何使用它們: 網絡
public async void IsolatedStorage() { // settings var _Name = \\"MyFileName"; var _Folder = Windows.Storage.ApplicationData.Current.LocalFolder; var _Option = Windows.Storage.CreationCollisionOption.ReplaceExisting; // create file var _File = await _Folder.CreateFileAsync(_Name, _Option); // write content var _WriteThis = \\"Hello world!\\"; await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis); // acquire file _File = await _Folder.GetFileAsync(_Name); // read content var _ReadThis = await Windows.Storage.FileIO.ReadTextAsync(_File); }
首先建立一個文件夾,在文件夾裏建立文件 private async void CreateButton_Click(object sender, RoutedEventArgs e) { string name=FileName.Text; //建立文件的名稱 folder =ApplicationData.Current.LocalFolder; StorageFolder tempFolder = await folder.CreateFolderAsync("Config",CreationCollisionOption.OpenIfExists); file =await tempFolder.CreateFileAsync(name,CreationCollisionOption.OpenIfExists); }
這裏介紹三種寫入文件的方式 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轉換成IBuffer類型的 await FileIO.WriteBufferAsync(file,buffer); break; } }
case"1": //以文本的方式讀取文件 content =await FileIO.ReadTextAsync(file);
break; case"2": //以流的方式讀取文件 IBuffer buffer = await FileIO.ReadBufferAsync(file); break; case"3": content = Convert(buffer);
break;
private IBuffer Convert(string text) //將string轉換成IBuffer類型的 { using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { using (DataWriter dataWriter = newDataWriter()) { dataWriter.WriteString(text); return dataWriter.DetachBuffer(); } } } private string Convert(IBuffer buffer) //將IBuffer轉換成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; }
IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);app
byte[] bytes=WindowsRuntimeBufferExtensions.ToArray(buffer,0,(int)buffer.Length);dom
Stream stream = WindowsRuntimeBufferExtensions.AsStream(buffer);async
若是你想要從你的工程中讀取一個資源文件,這個文件大多數狀況下是示例數據或者設置等.可能會是XML文件,JSON文件,或者其它格式.能讀取嗎?固然能夠.ui
注意:工程中的文件是不能進行寫操做的。要想對工程中的文件進行寫操做,須要將其copy到獨立存儲中,或者其餘地方,而後再進行寫操做。this
第一步 添加文件到工程中.注意:這是你的文件,你須要處理文件類型.以下圖,我添加了一個MyFile.txt文件到MyFolder目錄中.spa
第二步3d
修改文件的生成操做爲內容.並將複製到輸出目錄修改成始終複製.這將確保文件在程序中.不這樣作的話,讀取不到文件.code
第三步
讀取文件內容,代碼以下:
private async void ProjectFile() { // settings var _Path = @"MyFolderMyFile.txt"; var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation; // acquire file var _File = await _Folder.GetFileAsync(_Path); // read content var _ReadThis = await Windows.Storage.FileIO.ReadTextAsync(_File); }
你想要從文檔庫中讀取文件?那麼就使用文件選取器來讓用戶選擇文件.
只須要這樣作:
爲了使用文件選取器,並不須要作特殊的事情。不要對AppXManifest進行任何改變(緣由:使用文件選取器是讓用戶作出選擇,只有用戶能夠選擇文件).所以選取器是對其本身能力的一種聲明和贊成.
下面是使用的代碼:
async void LocalFileFromPicker() { // 初始化文件選擇器
var _Picker = new FileOpenPicker { ViewMode = PickerViewMode.List, SuggestedStartLocation = PickerLocationId.DocumentsLibrary, }; _Picker.FileTypeFilter.Add(「.txt」);//添加選擇什麼類型的文件// 啓動文件選擇器
var _File = await _Picker.PickSingleFileAsync(); if (_File == null) { await new Windows.UI.Popups.MessageDialog("No file").ShowAsync(); return; } // 讀取文件屬性
var _Message = string.Format(\\"File date: {0}\\", (await _File.GetBasicPropertiesAsync()).DateModified); await new Windows.UI.Popups.MessageDialog(_Message).ShowAsync(); // 讀取選擇文件內容
var _Content = await Windows.Storage.FileIO.ReadTextAsync(_File); await new Windows.UI.Popups.MessageDialog(_Content).ShowAsync(); }
在上面的代碼中,首先初始化了一個FileOpenPicker.而後調用選取器的PickSingleFileAsync()方法來獲取一個StorageFile。接着使用MessageDialog來顯示一些詳細內容。
若是你不想經過文件選取器來讀取文件,能作到嗎?答案是yes.不過稍微有點複雜,由於須要修改程序的AppXManifest文件,來請求文檔庫的訪問功能.
以下圖
將文檔庫訪問勾上.這是你可能注意到了功能Tab標題有個紅色的X.這表示有錯誤.如何修改呢.
須要修改聲明Tab裏面的文件類型
注意,文件類型的設置不能是*.*
以下圖(這裏我只訪問txt文件,因此只添加.txt)
如今,能夠讀取文件內容了
下面的代碼我建立了一個HelloWorld.txt文件,並進行了讀寫操做.最後,我將該文件刪除
async void LocalFileWithoutPicker() { var _Name = "HelloWorld.txt"; var _Folder = KnownFolders.DocumentsLibrary; var _Option = Windows.Storage.CreationCollisionOption.ReplaceExisting; // create file var _File = await _Folder.CreateFileAsync(_Name, _Option); // write content var _WriteThis = "Hello world!"; await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis); // acquire file try { _File = await _Folder.GetFileAsync(_Name); } catch (FileNotFoundException) { /* TODO */ } // read content var _Content = await FileIO.ReadTextAsync(_File); await new Windows.UI.Popups.MessageDialog(_Content).ShowAsync(); await _File.DeleteAsync(); }
面的代碼能夠很好的運行,那是由於我在AppXManifest文件中聲明瞭從文檔庫文件夾中讀取txt文件的功能.
若是你在manifest中請求了以下功能:文檔,圖片,音樂,視頻等,那麼能夠在庫中枚舉出這些文件.須要注意的是返回某個文件夾中的文件將根據manifest中聲明的文件類型被自動過濾.
/// <summary> /// 是否採用默認關聯程序打開文件 /// </summary> /// <param name="withPicker"></param> public async void OpenFile( bool withPicker) { StorageFolder storageFolder = KnownFolders.DocumentsLibrary; StorageFile file = await storageFolder.CreateFileAsync("網絡.pdf", CreationCollisionOption.ReplaceExisting); if (file != null) { if (withPicker) { //請用戶選擇打開方式 var options = new LauncherOptions { DisplayApplicationPicker = true }; options.UI.PreferredPlacement = Placement.Below; await Launcher.LaunchFileAsync(file, options); } else { //直接使用默認關聯程序打開 await Launcher.LaunchFileAsync(file); } } }
string uriToLaunch = @\\"http://www.DevDiv.com\\"; // Create a Uri object from a URI string var uri = new Uri(uriToLaunch); // Launch the URI var success = await Windows.System.Launcher.LaunchUriAsync(uri); // Launch a URI.直接打開 private async void LaunchUriButton_Click(object sender, RoutedEventArgs e) { var uri = new Uri(uriToLaunch); bool success = await Windows.System.Launcher.LaunchUriAsync(uri); } // Launch a URI. Show a warning prompt.顯示提醒框 private async void LaunchUriWithWarningButton_Click(object sender, RoutedEventArgs e) { var uri = new Uri(uriToLaunch); LauncherOptions options = new LauncherOptions();// Configure the warning prompt. options.TreatAsUntrusted = true; bool success = await Launcher.LaunchUriAsync(uri, options); } // Launch a URI. Show an Open With dialog that lets the user chose the handler to use.//用戶選擇打開,在你單擊控件下面,顯示應用列表
private async void LaunchUriOpenWithButton_Click(object sender, RoutedEventArgs e) { var uri = new Uri(uriToLaunch); Point openWithPosition = GetOpenWithPosition(this.LaunchUriOpenWithButton); var options = new LauncherOptions(); options.DisplayApplicationPicker = true; options.UI.InvocationPoint = openWithPosition; options.UI.PreferredPlacement = Placement.Below; bool success = await Windows.System.Launcher.LaunchUriAsync(uri, options); } // The Open With dialog should be displayed just under the element that triggered it.//獲取控件下邊緣的中點
private Windows.Foundation.Point GetOpenWithPosition(FrameworkElement element) { Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null); Point desiredLocation = buttonTransform.TransformPoint(new Point());//獲取控件左上角的座標 desiredLocation.X = desiredLocation.X + element.ActualWidth / 2; desiredLocation.Y = desiredLocation.Y + element.ActualHeight; return desiredLocation; }