在 Windows Phone 8.1 中,增加了 FilePicker 的方式与文件打交道,最大的亮点在于这种方式不仅可以浏览手机上的文件,还可以浏览符合协议的应用里的文件

比如点击 OneDrive 就会打开 OneDrive 应用:


(1)FileOpenPicker

FileOpenPicker 也就是选择文件,可以设置打开单选界面或多选界面。

1)实例化 FileOpenPicker 对象,并设置 ContinuationData

private void openFileButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker imageOpenPicker = new FileOpenPicker(); imageOpenPicker.FileTypeFilter.Add(".jpg");
imageOpenPicker.FileTypeFilter.Add(".png");
    
imageOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; imageOpenPicker.ContinuationData["Operate"] = "OpenImage"; imageOpenPicker.PickSingleFileAndContinue();
}

FileOpenPicker 可以设置 FileTypeFilter,方便文件的浏览;还可以设置选择界面的开始目录(SuggestedStartLocation)。

因为在打开选择文件的界面后当前应用会挂起,所以需要 ContinuationData 来记录一些信息,以保证当应用恢复时能够保持之前的信息。

2)重写 App.xaml.cs 的 OnActivated 方法

当用户选择了文件之后会返回到之前的应用,这时需要重写 OnActivated 方法让应用跳转到指定页面,并传递用户选择的文件。

protected override void OnActivated(IActivatedEventArgs args)
{
if( args is FileOpenPickerContinuationEventArgs )
{
Frame rootFrame = Window.Current.Content as Frame; if( rootFrame == null )
{
rootFrame = new Frame(); rootFrame.CacheSize = ; Window.Current.Content = rootFrame;
} if( rootFrame.Content == null )
{
if( rootFrame.ContentTransitions != null )
{
this.transitions = new TransitionCollection();
foreach( var c in rootFrame.ContentTransitions )
{
this.transitions.Add(c);
}
} rootFrame.ContentTransitions = null;
rootFrame.Navigated += this.RootFrame_FirstNavigated; if( !rootFrame.Navigate(typeof(MainPage)) )
{
throw new Exception("Failed to create first page");
}
} if( !rootFrame.Navigate(typeof(MainPage)) )
{
throw new Exception("Failed to create target page");
} MainPage targetPage = rootFrame.Content as MainPage;
targetPage.FilePickerEventArgs = (FileOpenPickerContinuationEventArgs)args; Window.Current.Activate();
}
}

首先是要判断之前的行为是不是 FileOpenPicker 引起的,然后获取 Frame 并跳转到指定页面,将包含用户选择文件的信息 args 传递到指定页面中。

3)添加 FileOpenPickerContinuationEventArgs 属性和 ContinuFileOpenPicker 方法

当应用将 args 传递到页面去后,剩下的就是处理文件了:

private FileOpenPickerContinuationEventArgs filePickerEventArgs;
public FileOpenPickerContinuationEventArgs FilePickerEventArgs
{
get { return filePickerEventArgs; }
set
{
filePickerEventArgs = value;
ContinuFileOpenPicker(filePickerEventArgs);
}
} private async void ContinuFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
if( args.ContinuationData["Operate"] as string == "OpenImage" && args.Files != null && args.Files.Count > )
{
StorageFile file = args.Files[]; BitmapImage image = new BitmapImage();
await image.SetSourceAsync(await file.OpenAsync(FileAccessMode.Read)); myImage.Source = image;
}
}

(2)AccessCache

AccessCache 也就是指对用户选择文件或文件夹的缓存,包括 MostRecentlyUsedList 和 FutureAccessList。

MostRecentlyUsedList 可以保存 25 项,并会根据用户使用情况自动排序,当新的进来后超过 25 项了则会自动将最旧的删除。

FutureAccessList 则可以保存 1000 项,但不会自动排序,需要开发者自行管理。

保存方法:

private async void ContinuFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
if( args.ContinuationData["Image"] as string == "OpenImage" && args.Files != null && args.Files.Count > )
{
StorageFile file = args.Files[]; BitmapImage image = new BitmapImage();
await image.SetSourceAsync(await file.OpenAsync(FileAccessMode.Read)); myImage.Source = image; StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "");
StorageApplicationPermissions.FutureAccessList.Add(file, "");
}
}

读取方法:

private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var mruList = StorageApplicationPermissions.MostRecentlyUsedList.Entries;
foreach( var item in mruList )
{
StorageFile file = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(item.Token); BitmapImage image = new BitmapImage();
await image.SetSourceAsync(await file.OpenAsync(FileAccessMode.Read)); Image img = new Image();
img.Source = image;
img.Stretch = Stretch.Uniform;
img.Margin = new Thickness(, , , );
imagesStackPanel.Children.Add(img);
}
}

开发者可以灵活使用这两个列表,方便用户浏览最近使用过的文件。

(3)FileSavePicker

既然有 OpenPicker,自然就有 SavePicker。

FileSavePicker 的使用方法与 FileOpenPicker 非常相似。

1)实例化 FileSavePicker 对象,并设置 ContinuationData

private void saveButton_Click(object sender, RoutedEventArgs e)
{
FileSavePicker imageSavePicker = new FileSavePicker(); imageSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
imageSavePicker.SuggestedFileName = "Test";
imageSavePicker.FileTypeChoices.Add("Txt", new List<string>() { ".txt" }); imageSavePicker.ContinuationData["Txt"] = "SaveTxt";
imageSavePicker.PickSaveFileAndContinue();
}

实例化 FileSavePicker 对象后,设置 FileName 和 FileType。

当用户选择了某个文件夹后,系统就会在该文件夹中新建一个该 FileName 和 FileType 的文件,并将该文件放到 FileSavePickerContinuationEventArgs 中。

2)重写 App.xaml.cs 的 OnActivated 方法

与 FileOpenPicker 一样,同样需要重写 OnActivated 方法,这次要检查的 args 类型为 FileSavePickerContinuationEventArgs:

protected override void OnActivated(IActivatedEventArgs args)
{
if( args is FileSavePickerContinuationEventArgs )
{
Frame rootFrame = Window.Current.Content as Frame; // 不要在窗口已包含内容时重复应用程序初始化,
// 只需确保窗口处于活动状态
if( rootFrame == null )
{
// 创建要充当导航上下文的框架,并导航到第一页
rootFrame = new Frame(); // TODO: 将此值更改为适合您的应用程序的缓存大小
rootFrame.CacheSize = ; if( args.PreviousExecutionState == ApplicationExecutionState.Terminated )
{
// TODO: 从之前挂起的应用程序加载状态
} // 将框架放在当前窗口中
Window.Current.Content = rootFrame;
} if( rootFrame.Content == null )
{
// 删除用于启动的旋转门导航。
if( rootFrame.ContentTransitions != null )
{
this.transitions = new TransitionCollection();
foreach( var c in rootFrame.ContentTransitions )
{
this.transitions.Add(c);
}
} rootFrame.ContentTransitions = null;
rootFrame.Navigated += this.RootFrame_FirstNavigated; // 当导航堆栈尚未还原时,导航到第一页,
// 并通过将所需信息作为导航参数传入来配置
// 新页面
if( !rootFrame.Navigate(typeof(MainPage)) )
{
throw new Exception("Failed to create initial page");
}
} if( !rootFrame.Navigate(typeof(MainPage)) )
{
throw new Exception("Failed to create target page");
} MainPage targetPage = rootFrame.Content as MainPage;
targetPage.SavePickerArgs = (FileSavePickerContinuationEventArgs)args; // 确保当前窗口处于活动状态
Window.Current.Activate();
}
}

OnActivated

3)添加 FileSavePickerContinuationEventArgs 属性和 ContinuFileSavePicker 方法

最后在 ContinuFileSavePicker 方法中对要保存的文件进行操作:

private FileSavePickerContinuationEventArgs savePickerArgs;
public FileSavePickerContinuationEventArgs SavePickerArgs
{
get { return savePickerArgs; }
set
{
savePickerArgs = value;
ContinuFileSavePicker(savePickerArgs);
}
} private async void ContinuFileSavePicker(FileSavePickerContinuationEventArgs args)
{
if( args.ContinuationData["Txt"] as string == "SaveTxt" && args.File != null )
{
StorageFile txt = args.File;
await FileIO.WriteTextAsync(txt, "");
}
}

Windows Phone 8.1 FilePicker API的更多相关文章

  1. Windows 和 Linux 的IPC API对应表

    原文出处:http://blog.csdn.net/zhengdy/article/details/5485472                                           ...

  2. Windows Phone 8 - Runtime Location API - 2

    原文:Windows Phone 8 - Runtime Location API - 2 在<Windows Phone 8 - Runtime Location API - 1>介绍基 ...

  3. Windows Phone 8 - Runtime Location API - 1

    原文:Windows Phone 8 - Runtime Location API - 1 在Windows Phone里要做Background Service的方式,除了Background Ag ...

  4. windows service承载的web api宿主搭建(Microsoft.Owin+service)

    今天突然想起改良一下以前搭建的“windows service承载的web api”服务,以前也是直接引用的类库,没有使用nuget包,时隔几年应该很旧版本了吧.所以本次把需要nuget获取的包记录一 ...

  5. 【windows核心编程】一个API拦截的例子

    API拦截 修改PE文件导入段中的导入函数地址 为 新的函数地址 这涉及PE文件格式中的导入表和IAT,PE文件中每个隐式链接的DLL对应一个IMAGE_IMPORT_DESCRIPTOR描述符结构, ...

  6. [Windows Azure] Using the Graph API to Query Windows Azure AD

    Using the Graph API to Query Windows Azure AD 4 out of 4 rated this helpful - Rate this topic This d ...

  7. Windows 10 16251 添加的 api

    本文主要讲微软最新的sdk添加的功能,暂时还不能下载,到 7月29 ,现在可以下载是 16232 ,支持Neon效果 实际上设置软件最低版本为 16232 就自动支持 Neon 效果. 主要添加了 A ...

  8. 在Windows 下如何使用 AspNetCore Api 和 consul

    一.概念:什么是consul: Consul 是有多个组件组成的一个整体,作用和Eureka,Zookeeper相当,都是用来做服务的发现与治理. Consul的特性: 1. 服务的发现:consul ...

  9. windows服务中对外提供API接口

    public class SendMqService { private static bool isExcute = true; private static HttpListener listen ...

随机推荐

  1. 一个发邮件的demo 用golang

    一个比较成熟的第三方包用来发邮件,可以带图片 和附件,项目地址 : github.com/go-gomail/gomail 一个发邮件的demo 用golang 文件目录树: -d:\test\goe ...

  2. MSSQL相关用法

    一.分页查询 方式一(row_number): SELECT TOP pageSize * FROM (SELECT row_number() OVER (ORDER BY orderColumn) ...

  3. HDU 2489 Minimal Ratio Tree(prim+DFS)

    Minimal Ratio Tree Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Other ...

  4. xcode6.3 模版位置

    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templ ...

  5. POJ 3061 Subsequence 二分或者尺取法

    http://poj.org/problem?id=3061 题目大意: 给定长度为n的整列整数a[0],a[1],--a[n-1],以及整数S,求出总和不小于S的连续子序列的长度的最小值. 思路: ...

  6. 毕业两年做到测试经理的经历总结- 各个端的自动化,性能测试结合项目具体场景实战,分析客户反馈的Bug

    前言 最近看到行业的前辈都分享一些过往的经历来指导我们这些测试人员,我很尊敬我们的行业前辈,没有他们在前面铺路,如今我们这帮年轻的测试人估计还在碰壁或摸着石头过河,结合前辈们的经验,作为年轻的测试人也 ...

  7. 关于mysql事务行锁for update实现写锁的功能

    关于mysql事务行锁for update实现写锁的功能 读后感:用切面编程的理论来讲,数据库的锁对于业务来说是透明的.spring的事务管理代码,业务逻辑代码,表锁,应该是三个不同的设计层面. 在电 ...

  8. Access WMI via Python from Linux

    You can use Impacket (https://github.com/CoreSecurity/impacket) that has WMI implemented in Python. ...

  9. VMware Ubuntu安装具体过程

    不是每个程序猿都必须玩过linux,仅仅是博主认为如今的非常多server都是linux系统的,而自己属于那种前端也搞.后台也搞,对框架搭建也感兴趣,可是非常多生产上的框架和工具都是安装在server ...

  10. msys 中打开系统程序

    按照msys 后发现sh自带的vim不好用,下载安装了个gvim,在etc/profile中作如下设置: alias gvim="D:/Program\ Files/Vim/vim73/gv ...