我尝试在UWP应用程序中创建和编写该文件。在第一次执行时它工作正常,第二次它覆盖第一个内容,文件只包含第二次执行的内容。
Windows.Storage.StorageFolder Location = ApplicationData.Current.LocalFolder;
var lstfiles = await Location.GetFilesAsync(CommonFileQuery.OrderByName);
var foundfile = lstfiles.Where(x => x.Name==Test.dat").FirstOrDefault();
if (foundfile==null)
{
StorageFile fil = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Test.dat");
//StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Test.dat");
using (IRandomAccessStream writeStream = await fil.OpenAsync(FileAccessMode.ReadWrite))
{
System.IO.Stream s = writeStream.AsStreamForWrite();
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Async = true;
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(s, settings))
{
writer.WriteStartElement("Order");
writer.WriteElementString("OrderID", "y1");
writer.WriteElementString("OrderTotal", "y2");
writer.WriteElementString("Customer", "y3");
writer.WriteElementString("Phone", "y4");
writer.Flush();
await writer.FlushAsync();
}
}
}
else
{
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Test.dat");
using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
System.IO.Stream s = writeStream.AsStreamForWrite();
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Async = true;
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(s, settings))
{
writer.WriteStartElement("Order");
writer.WriteElementString("OrderID", "v51");
writer.WriteElementString("OrderTotal", "v2");
writer.WriteElementString("Customer", "v3");
writer.WriteElementString("Phone", "v4");
// await FileIO.AppendTextAsync(file, writer.ToString());
writer.Flush();
await writer.FlushAsync();
}
}
}
答案 0 :(得分:1)
虽然在能够添加新节点之前必须阅读整个Xml,但无论性能如何,更简洁的方法是使用
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Test.dat", CreationCollisionOption.OpenIfExists);
var info = await file.GetBasicPropertiesAsync();
XDocument xDocument = null;
if(info.Size > 0)
/* read existing file here */
else
/* create an empty document here */
XElement root = xDocument.Element("Root");
IEnumerable<XElement> rows = root.Descendants("Order");
XElement firstRow = rows.First();
firstRow.AddBeforeSelf(
new XElement("Order",
new XElement("OrderID", "y1"),
new XElement("OrderTotal", "y2"),
new XElement("Customer", "y3"),
new XElement("Phone", "y4")));
await FileIO.WriteTextAsync(file, xDocument.ToString());
这样您就没有代码重复。
答案 1 :(得分:-1)
您可以使用Linq Xml
<div class="button">
</div>
<div class="button">Button
</div>
<div class="button">
</div>