简体   繁体   English

如何在Windows Phone 8中将文本写入文件?

[英]How to write text to a file in Windows Phone 8?

I found this example of how to write data to a file in Windows Phone 8: 我找到了如何将数据写入Windows Phone 8中的文件的示例:

https://stackoverflow.com/a/15625701/181771 https://stackoverflow.com/a/15625701/181771

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

This works, but the text is encoded. 这有效,但文本是编码的。 I'm attempting to write a JSON file so I'd like to save the raw text. 我正在尝试编写一个JSON文件,所以我想保存原始文本。

What do I need to do to accomplish this? 我需要做些什么才能做到这一点?

Use StreamWriter that will automatically deal with the encoding. 使用将自动处理编码的StreamWriter

public async Task WriteDataToFileAsync(string fileName, string content)
{
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

using (var s = await file.OpenStreamForWriteAsync())
{
    using (var writer = new StreamWriter(s))
    {
        await writer.WriteAsync(content);
    }
} 
}

Try to use JSON.NET it is pretty simple serialize with this 尝试使用JSON.NET,这很简单

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Sizes": [
//    "Small"
//  ]
//}

Then save the string named json to file. 然后将名为json的字符串保存到文件中。

You will find more helpful stuff here http://james.newtonking.com/json/help/index.html 你会在http://james.newtonking.com/json/help/index.html找到更多有用的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM