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

后端 未结 2 929
孤城傲影
孤城傲影 2020-12-04 00:16

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 met

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 00:38

    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 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");
    

提交回复
热议问题