每个Metro程序都有三个文件夹:Local,Roaming,Temp。每个文件夹的访问方法都是相同的.
下面的代码是如何使用它们:
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);
byte[] bytes=WindowsRuntimeBufferExtensions.ToArray(buffer,0,(int)buffer.Length);
Stream stream = WindowsRuntimeBufferExtensions.AsStream(buffer);
如果你想要从你的工程中读取一个资源文件,这个文件大多数情况下是示例数据或者设置等.可能会是XML文件,JSON文件,或者其它格式.能读取吗?当然可以.
注意:工程中的文件是不能进行写操作的。要想对工程中的文件进行写操作,需要将其copy到独立存储中,或者其他地方,然后再进行写操作。
第一步 添加文件到工程中.注意:这是你的文件,你需要处理文件类型.如下图,我添加了一个MyFile.txt文件到MyFolder目录中.
第二步
修改文件的生成操作为内容.并将复制到输出目录修改为始终复制.这将确保文件在程序中.不这样做的话,读取不到文件.
第三步
读取文件内容,代码如下:
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; }