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

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


(1)FileOpenPicker

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

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

  1. private void openFileButton_Click(object sender, RoutedEventArgs e)
  2. {
  3. FileOpenPicker imageOpenPicker = new FileOpenPicker();
  4.  
  5. imageOpenPicker.FileTypeFilter.Add(".jpg");
  6. imageOpenPicker.FileTypeFilter.Add(".png");
        
    imageOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
  7.  
  8. imageOpenPicker.ContinuationData["Operate"] = "OpenImage";
  9.  
  10. imageOpenPicker.PickSingleFileAndContinue();
  11. }

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

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

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

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

  1. protected override void OnActivated(IActivatedEventArgs args)
  2. {
  3. if( args is FileOpenPickerContinuationEventArgs )
  4. {
  5. Frame rootFrame = Window.Current.Content as Frame;
  6.  
  7. if( rootFrame == null )
  8. {
  9. rootFrame = new Frame();
  10.  
  11. rootFrame.CacheSize = ;
  12.  
  13. Window.Current.Content = rootFrame;
  14. }
  15.  
  16. if( rootFrame.Content == null )
  17. {
  18. if( rootFrame.ContentTransitions != null )
  19. {
  20. this.transitions = new TransitionCollection();
  21. foreach( var c in rootFrame.ContentTransitions )
  22. {
  23. this.transitions.Add(c);
  24. }
  25. }
  26.  
  27. rootFrame.ContentTransitions = null;
  28. rootFrame.Navigated += this.RootFrame_FirstNavigated;
  29.  
  30. if( !rootFrame.Navigate(typeof(MainPage)) )
  31. {
  32. throw new Exception("Failed to create first page");
  33. }
  34. }
  35.  
  36. if( !rootFrame.Navigate(typeof(MainPage)) )
  37. {
  38. throw new Exception("Failed to create target page");
  39. }
  40.  
  41. MainPage targetPage = rootFrame.Content as MainPage;
  42. targetPage.FilePickerEventArgs = (FileOpenPickerContinuationEventArgs)args;
  43.  
  44. Window.Current.Activate();
  45. }
  46. }

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

3)添加 FileOpenPickerContinuationEventArgs 属性和 ContinuFileOpenPicker 方法

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

  1. private FileOpenPickerContinuationEventArgs filePickerEventArgs;
  2. public FileOpenPickerContinuationEventArgs FilePickerEventArgs
  3. {
  4. get { return filePickerEventArgs; }
  5. set
  6. {
  7. filePickerEventArgs = value;
  8. ContinuFileOpenPicker(filePickerEventArgs);
  9. }
  10. }
  11.  
  12. private async void ContinuFileOpenPicker(FileOpenPickerContinuationEventArgs args)
  13. {
  14. if( args.ContinuationData["Operate"] as string == "OpenImage" && args.Files != null && args.Files.Count > )
  15. {
  16. StorageFile file = args.Files[];
  17.  
  18. BitmapImage image = new BitmapImage();
  19. await image.SetSourceAsync(await file.OpenAsync(FileAccessMode.Read));
  20.  
  21. myImage.Source = image;
  22. }
  23. }

(2)AccessCache

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

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

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

保存方法:

  1. private async void ContinuFileOpenPicker(FileOpenPickerContinuationEventArgs args)
  2. {
  3. if( args.ContinuationData["Image"] as string == "OpenImage" && args.Files != null && args.Files.Count > )
  4. {
  5. StorageFile file = args.Files[];
  6.  
  7. BitmapImage image = new BitmapImage();
  8. await image.SetSourceAsync(await file.OpenAsync(FileAccessMode.Read));
  9.  
  10. myImage.Source = image;
  11.  
  12. StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "");
  13. StorageApplicationPermissions.FutureAccessList.Add(file, "");
  14. }
  15. }

读取方法:

  1. private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
  2. {
  3. var mruList = StorageApplicationPermissions.MostRecentlyUsedList.Entries;
  4. foreach( var item in mruList )
  5. {
  6. StorageFile file = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(item.Token);
  7.  
  8. BitmapImage image = new BitmapImage();
  9. await image.SetSourceAsync(await file.OpenAsync(FileAccessMode.Read));
  10.  
  11. Image img = new Image();
  12. img.Source = image;
  13. img.Stretch = Stretch.Uniform;
  14. img.Margin = new Thickness(, , , );
  15. imagesStackPanel.Children.Add(img);
  16. }
  17. }

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

(3)FileSavePicker

既然有 OpenPicker,自然就有 SavePicker。

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

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

  1. private void saveButton_Click(object sender, RoutedEventArgs e)
  2. {
  3. FileSavePicker imageSavePicker = new FileSavePicker();
  4.  
  5. imageSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
  6. imageSavePicker.SuggestedFileName = "Test";
  7. imageSavePicker.FileTypeChoices.Add("Txt", new List<string>() { ".txt" });
  8.  
  9. imageSavePicker.ContinuationData["Txt"] = "SaveTxt";
  10. imageSavePicker.PickSaveFileAndContinue();
  11. }

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

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

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

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

  1. protected override void OnActivated(IActivatedEventArgs args)
  2. {
  3. if( args is FileSavePickerContinuationEventArgs )
  4. {
  5. Frame rootFrame = Window.Current.Content as Frame;
  6.  
  7. // 不要在窗口已包含内容时重复应用程序初始化,
  8. // 只需确保窗口处于活动状态
  9. if( rootFrame == null )
  10. {
  11. // 创建要充当导航上下文的框架,并导航到第一页
  12. rootFrame = new Frame();
  13.  
  14. // TODO: 将此值更改为适合您的应用程序的缓存大小
  15. rootFrame.CacheSize = ;
  16.  
  17. if( args.PreviousExecutionState == ApplicationExecutionState.Terminated )
  18. {
  19. // TODO: 从之前挂起的应用程序加载状态
  20. }
  21.  
  22. // 将框架放在当前窗口中
  23. Window.Current.Content = rootFrame;
  24. }
  25.  
  26. if( rootFrame.Content == null )
  27. {
  28. // 删除用于启动的旋转门导航。
  29. if( rootFrame.ContentTransitions != null )
  30. {
  31. this.transitions = new TransitionCollection();
  32. foreach( var c in rootFrame.ContentTransitions )
  33. {
  34. this.transitions.Add(c);
  35. }
  36. }
  37.  
  38. rootFrame.ContentTransitions = null;
  39. rootFrame.Navigated += this.RootFrame_FirstNavigated;
  40.  
  41. // 当导航堆栈尚未还原时,导航到第一页,
  42. // 并通过将所需信息作为导航参数传入来配置
  43. // 新页面
  44. if( !rootFrame.Navigate(typeof(MainPage)) )
  45. {
  46. throw new Exception("Failed to create initial page");
  47. }
  48. }
  49.  
  50. if( !rootFrame.Navigate(typeof(MainPage)) )
  51. {
  52. throw new Exception("Failed to create target page");
  53. }
  54.  
  55. MainPage targetPage = rootFrame.Content as MainPage;
  56. targetPage.SavePickerArgs = (FileSavePickerContinuationEventArgs)args;
  57.  
  58. // 确保当前窗口处于活动状态
  59. Window.Current.Activate();
  60. }
  61. }

OnActivated

3)添加 FileSavePickerContinuationEventArgs 属性和 ContinuFileSavePicker 方法

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

  1. private FileSavePickerContinuationEventArgs savePickerArgs;
  2. public FileSavePickerContinuationEventArgs SavePickerArgs
  3. {
  4. get { return savePickerArgs; }
  5. set
  6. {
  7. savePickerArgs = value;
  8. ContinuFileSavePicker(savePickerArgs);
  9. }
  10. }
  11.  
  12. private async void ContinuFileSavePicker(FileSavePickerContinuationEventArgs args)
  13. {
  14. if( args.ContinuationData["Txt"] as string == "SaveTxt" && args.File != null )
  15. {
  16. StorageFile txt = args.File;
  17. await FileIO.WriteTextAsync(txt, "");
  18. }
  19. }

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. Bitmap Image Graphics

    Bitmap Image  Graphics private void DrawImagePointF(PaintEventArgs e){ // Create image.    Image new ...

  2. POJ 2253-Frogger (Prim)

    题目链接:Frogger 题意:两仅仅青蛙,A和B,A想到B哪里去,可是A得弹跳有限制,所以不能直接到B,可是有其它的石头作为过渡点,能够通过他们到达B,问A到B的全部路径中.它弹跳最大的跨度的最小值 ...

  3. js 数组操作大集合

    js数组的操作 用 js有非常久了,但都没有深究过js的数组形式.偶尔用用也就是简单的string.split(char).这段时间做的一个项目.用到数组的地方非常多.自以为js高手的自己竟然无从下手 ...

  4. hdu 2795 Billboard(线段树单点更新)

    Billboard Time Limit: 20000/8000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  5. FreeNX

    freenx 在Linux下,我们最常使用的远程管理工具是ssh客户端,比如putty.SecureCRT等,但是ssh只提供字符界面的操作方式,有时我们需要图形界面的操作,在Linux下支持图形界面 ...

  6. Solr 读数据流程

    Solr 读数据流程: 1.用户提供搜索关键词,也就是搜索语句,需要经过分词器处理以及语言处理. 2.对处理之后的关键词,搜索索引找出对应Document 即记录. 3.用户根据需要从找到的Docum ...

  7. redhat6.5安装10201解决办法

    rpm --import /etc/pki/rpm-gpg/RPM*yum install -y  --skip-broken compat-libstdc++* elfutils-libelf* g ...

  8. Java web开发了解

    1.什么是Java web项目? F.A.Q: 服务器 服务器,也称伺服器,是提供计算服务的设备.由于服务器需要响应服务请求,并进行处理,因此一般来说服务器应具备承担服务并且保障服务的能力.服务器的构 ...

  9. AsyncCallback BeginInvode endinvode 异步调用

    下面是搜藏的代码: //首先准备好,要进行C#异步调用的方法(能C#异步调用的,最好不多线程) private string MethodName(int Num, out int Num2) { N ...

  10. 00092_字符输出流Writer

    1.字符输出流Writer (1)既然有专门用于读取字符的流对象,那么肯定也有写的字符流对象: (2)查阅API,发现有一个Writer类,Writer是写入字符流的抽象类.其中描述了相应的写的动作. ...