• WP8开发系列3:WP7与WP8在文件IO操作上的区别


    引言:

    微软说明WP7应用程序可以兼容在WP8系统中运行,WP8又与WIN8共享同一个内核,这就意味着WP7时开发的应用可以向上兼容到WP8, WP8开发的应用可以迁移到Win8中, 那么,对于WP7与WP8在文件IO操作上又有哪些区别与共性呢?本篇为您揭晓一二。

    一、Windows Phone 7的文件操作:

    如果在现有的wp7开发平台上去写入一个文件,我们会想到使用: IsolatedStorageFile

    代码如下:

    private void WriteFile(string fileName, string content)
    {
        using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.CreateFile(fileName))
            {
                using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream))
                {
                    streamWriter.Write(content);
                }
            }
        }
    }

    读取一个文件:

    private string ReadFile(string fileName)
    {
        string text;
        using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.OpenFile(fileName, FileMode.Open))
            {
                using (StreamReader streamReader = new StreamReader(isolatedStorageFileStream))
                {
                    text = streamReader.ReadToEnd();
                }
            }
        }
        return text;
    }

    然后,可以用IsoStoreSpy这类辅助工具进应用程序查看存储的文件的内容等操作.

    二、Windows Phone 8 文件操作

    wp8与win8的文件操作方式类似,如果你在win8下写过文件操作,那么WP8自然熟悉,这需要用到2个接口:IStorageFile和 IStorageFolder, 可以看出,一个是对文件的操作,一个是对目录的。这两个接口均在 :Windwos.Storage组件中,

    注意:因在windows 8 开发中大量使用了WinRT异步编程方式,故在WP8中编程亦如此。

    写入文件:

    public async Task WriteFile(string fileName, string text)
    {
        IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
     
        IStorageFile storageFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
     
        using (Stream stream = await storageFile.OpenStreamForWriteAsync())
        {
            byte[] content = Encoding.UTF8.GetBytes(text);
            await stream.WriteAsync(content, 0, content.Length);
        }
    }

    读取文件:

    public async Task<string> ReadFile(string fileName)
    {
        string text;
        IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
     
        IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName);
     
        IRandomAccessStream accessStream = await storageFile.OpenReadAsync();
     
        using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
        {
            byte[] content = new byte[stream.Length];
            await stream.ReadAsync(content, 0, (int) stream.Length);
     
            text = Encoding.UTF8.GetString(content, 0, content.Length);
        }
        return text;
    }

    OK,到此我们将操作文件的方法写好后,就可以在业务层进行调用了,方式如下:

    await WriteFile("TestWP8IO.txt", "测试WP8与WP7文件操作");
    string text = await ReadFile("TestWP8IO.txt")

    三、兼容性问题

    上面的代码分别对WP7与WP8平台的文件写入与读取操作进行了简单的说明,你可能会想:“我在WP7应用中的文件目录结构定义,是不是在WP8中也是一样的呢?”其实,两者是有点区别的,这点区别,也是日后WP7向WP8迁移过程中必须要考虑的元素之一。

    在WP7中,创建文件userinfo.txt,那么,它在隔离存储区的文件目录结构如下:

    C:\Data\Users\DefaultAppAccount\AppData\{ProductID}\Local\IsolatedStore\userinfo.txt

    在WP8中,创建相同文件,文件存储目录结构如下:

    C:\Data\Users\DefaultAppAccount\AppData\{ProductID}\Local\userinfo.txt

    两者一对比,我们很直观的就能看到区别在哪里,这就意味着:在WP8开发中,使用现有的WP7代码时,如果你不想改变原有文件目录结构,那你就必须要首先获取WP7隔离存储目录.即:

    IStorageFolder applicationFolder =await ApplicationData.Current.LocalFolder.GetFolderAsync("IsolatedStore");

    最后,想说明的是:

    如果你想“偷懒”或者说减少开发工作量,就看看我上面说的这些,但我建议各位开发者,最好是全新开发基于WP8平台的应用,毕竟这意味着你也可以在Win8中快速部署。

    原文地址:http://jasonwei.com/archives/463

    再续:

    打开文件(需要你的手机上面装有这样的应用程序,例如PDF|OneNote)

     IAsyncOperation<StorageFile> getFile = ApplicationData.Current.LocalFolder.GetFileAsync(filePath);
     getFile.Completed = (IAsyncOperation<StorageFile> asyncInfo, AsyncStatus asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        IStorageFile file = getFile.GetResults();
                        IAsyncOperation<bool> isLaunch = Windows.System.Launcher.LaunchFileAsync(file);
                        isLaunch.Completed = (IAsyncOperation<bool> asyncInfo_launch, AsyncStatus asyncStatus_launch) =>
                        {
                            if (asyncStatus_launch == AsyncStatus.Completed)
                            {
                                Debug.WriteLine("isLaunch:" + isLaunch);
                            }
     
                        };
                    }
                };

    Launcher.LaunchFileAsync(IStorageFile) | launchFileAsync(IStorageFile) Method (Windows)

    启动与指定的文件相关联的默认应用程序。

    public static IAsyncOperation<bool> LaunchFileAsync( IStorageFile file )

    参数

    file

    类型: IStorageFile

    文件。

    返回值

    类型: IAsyncOperation<Boolean>

    生成操作。

    备注

    当调用 API 时,调用应用程序必须对用户可见。

    此 API 也对它可生成的文件类型有若干限制。很多包含可执行代码的文件类型,例如 .exe、.msi 和 .js 文件,在启动时都被阻止。恶意文件会修改系统,此限制可保护用户免受可能存在的恶意文件的危害。

    当对上述任何原因生成失败时,API 成功并从其异步操作的 FALSE 返回。 因为其无法查询上述限制是否应用于当前生成,调用应用程序不应假定已成功生成,而应提供失败时的回退机制。可能的解决方案将是要求用户保存文件并指导用户在桌面打开它。

    若要使用户选择应用程序而不是生成默认应用程序,请设置 LauncherOptions.DisplayApplicationPicker | displayApplicationPicker 属性。

    若要显示文件可能不安全的警告,请设置 LauncherOptions.TreatAsUntrusted | treatAsUntrusted 属性。

    文件被传递给关联的应用程序。如果关联的应用程序为桌面应用程序,则使用外壳执行机制传递文件。

    示例

    此示例使用 LaunchFileAsync(IStorageFile) | launchFileAsync(IStorageFile) 生成包含在应用程序包中的文件。

    async void DefaultLaunch()
    {
       // Path to the file in the app package to launch
       string imageFile = @"images\test.png";
    
       var file = wait Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
    
       if (file != null)
       {
          // Launch the retrieved file
          var success = await Windows.System.Launcher.LaunchFileAsync(file);
    
          if (success)
          {
             // File launched
          }
          else
          {
             // File launch failed
          }
       }
       else
       {
          // Could not find file
       }
    }
    
     
  • 相关阅读:
    又见Dooyoul
    用premake编译跨平台opencv程序
    [try it] 使用Apache Ant
    用OllyDbg做破解
    什么是SEO
    SEO最新百度排名算法调整
    SEO网站外链的建设
    SEO网站title优化
    网站title优化应注意的细节
    [ios]设置ARC 【转】
  • 原文地址:https://www.cnblogs.com/Yukang1989/p/2720090.html
Copyright © 2020-2023  润新知