我是WP8上的新手并尝试构建一个应用程序,该应用程序从XML文件中读取常量变量并将用户更改写入另一个xml文件。
但是,我无法使用以下代码创建文件夹或文件。
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
this.writeFile();
}
public async void writeFile()
{
XDocument xDoc = XDocument.Load("Values.xml");
lblSafakCount.Text = xDoc.Descendants("isFirstUse").FirstOrDefault().Value.ToString();
string input = @"<isFirstUse>NO</isFirstUse>";
var replacement = XElement.Parse(input);;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
StorageFolder local = ApplicationData.Current.LocalFolder;
if (local != null)
{
StorageFolder sf = await local.CreateFolderAsync("Res", CreationCollisionOption.ReplaceExisting);
StorageFile file = await sf.CreateFileAsync("val.xml", CreationCollisionOption.OpenIfExists);
using (var stream = await file.OpenStreamForWriteAsync())
{
stream.Seek(0, SeekOrigin.End);
stream.Write(bytes, 0, bytes.Length);
}
}
}
我已成功读取Values.xml中的isFirstUse参数,因此从文件读取时没有问题。当我尝试逐步检查代码时,app在测试期间不会抛出任何错误,但不会创建文件夹或文件。
你能帮帮忙吗? 感谢。答案 0 :(得分:1)
以下是根据您的功能进行的读写操作
如果您想写入SD卡,可以在此处找到更多信息 Access the SD card in Windows Phone
public async void MyWriteFile()
{
string input = @"<isFirstUse>NO</isFirstUse>";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
StorageFolder local = ApplicationData.Current.LocalFolder;
if (local != null)
{
StorageFolder sf = await local.CreateFolderAsync("Res", CreationCollisionOption.ReplaceExisting);
StorageFile file = await sf.CreateFileAsync("val.xml", CreationCollisionOption.OpenIfExists);
using (var stream = await file.OpenStreamForWriteAsync())
{
stream.Seek(0, SeekOrigin.End);
stream.Write(bytes, 0, bytes.Length);
}
}
}
private async void MyReadFile()
{
byte[] bytes = new byte[256];
StorageFolder local = ApplicationData.Current.LocalFolder;
if (local != null)
{
StorageFolder sf = await local.CreateFolderAsync("Res", CreationCollisionOption.OpenIfExists);
StorageFile file = await sf.CreateFileAsync("val.xml", CreationCollisionOption.OpenIfExists);
using (var stream = await file.OpenStreamForReadAsync())
{
stream.Read(bytes, 0, 256);
}
}
}