Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

c# - How to properly read and write a file using Windows.Storage on Windows Phone 8

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a simple example:

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;
    }
}

use them like this:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...