如何在 Windows Phone 8 上使用 Windows.Storage 正确读取和写入文件 [英] How to properly read and write a file using Windows.Storage on Windows Phone 8

查看:18
本文介绍了如何在 Windows Phone 8 上使用 Windows.Storage 正确读取和写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要使用 Windows.Storage API 在 Windows Phone 8 中简单地写入文件和读取文件即可.使用旧的IsolatedStorage 方法相对容易,但使用新的WinRT API 证明要困难得多.

I'm needing to just simply write to a file and read from a file in Windows Phone 8 using the Windows.Storage APIs. This is relatively easy using the old IsolatedStorage method, but it's proving significantly harder using the new WinRT API.

我一直在尝试编写它,但似乎有所有这些奇怪的东西,比如 IBuffer.诸如此类.使用完整版的 WinRT,使用 Windows.Storage.FileIO 非常容易,它似乎存在以防止像我这样的开发人员发疯.但是,它没有在电话版本中实现.另外,我看了一个 Channel9 视频显示了一些代码示例,但他们有一个错误,因为他们使用了标记为安全的方法获得定期流至关重要.显然,不允许获得常规的 Stream.

I've been trying to write it, but there seem to be all these weird things like IBuffer. and such. Using the full version of WinRT, it's quite easy using Windows.Storage.FileIO which appears to exist to keep developers like me from going insane. However, it's not implemented in the Phone version. Also, I watched a Channel9 video which showed some code samples, but they had a mistake in that they used methods marked Security Critical to get regular streams. Apparently getting a regular Stream just isn't allowed.

那么,有人可以向我提供有关如何将文件读入字符串以及如何将字符串写入文件的简明正确的片段,以及正确的使用和处理技术吗?

So, can someone provide me with a concise and correct snippet on how to just read a file into a string and how to write a string to a file, complete with proper using and disposal techniques?

推荐答案

这是一个简单的例子:

public async Task WriteDataToFileAsync(string fileName, string content)
{
    byte[] data = Encoding.Unicode.GetBytes(content);

    var folder = ApplicationData.Current.LocalFolder;
    var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

    using (var s = await file.OpenStreamForWriteAsync())
    {
        await s.WriteAsync(data, 0, data.Length);
    }
}

public async Task<string> ReadFileContentsAsync(string fileName)
{
    var folder = ApplicationData.Current.LocalFolder;

    try
    {
        var file = await folder.OpenStreamForReadAsync(fileName);

        using (var streamReader = new StreamReader(file))
        {
            return streamReader.ReadToEnd();
        }
    }
    catch (Exception)
    {
        return string.Empty;
    }
}

像这样使用它们:

await this.WriteDataToFileAsync("afile.txt", "some text to save in a file");

var contents = await this.ReadFileContentsAsync("afile.txt");

这篇关于如何在 Windows Phone 8 上使用 Windows.Storage 正确读取和写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆