本文整理匯總了C#中Windows.Data.Xml.Dom.XmlDocument.SaveToFileAsync方法的典型用法代碼示例。如果您正苦於以下問題:C# XmlDocument.SaveToFileAsync方法的具體用法?C# XmlDocument.SaveToFileAsync怎麽用?C# XmlDocument.SaveToFileAsync使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Windows.Data.Xml.Dom.XmlDocument
的用法示例。
在下文中一共展示了XmlDocument.SaveToFileAsync方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: doAuditing
private async void doAuditing(Order order)
{
List<OrderItem> ageRestrictedItems = findAgeRestrictedItems(order);
if (ageRestrictedItems.Count > 0)
{
try
{
StorageFile file = await KnownFolders.DocumentsLibrary.CreateFileAsync("audit-" + order.OrderID.ToString() + ".xml");
if (file != null)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Order");
root.SetAttribute("ID", order.OrderID.ToString());
root.SetAttribute("Date", order.Date.ToString());
foreach (OrderItem orderItem in ageRestrictedItems)
{
XmlElement itemElement = doc.CreateElement("Item");
itemElement.SetAttribute("Product", orderItem.Item.Name);
itemElement.SetAttribute("Description", orderItem.Item.Description);
root.AppendChild(itemElement);
}
doc.AppendChild(root);
await doc.SaveToFileAsync(file);
}
else
{
MessageDialog dlg = new MessageDialog(String.Format("Unable to save to file: {0}", file.DisplayName), "Not saved");
dlg.ShowAsync();
}
}
catch (Exception ex)
{
MessageDialog dlg = new MessageDialog(ex.Message, "Exception");
dlg.ShowAsync();
}
finally
{
if (this.AuditProcessingComplete != null)
{
this.AuditProcessingComplete(String.Format(
"Audit record written for Order {0}", order.OrderID));
}
}
}
}
示例2: CheckGoodsFile
private async void CheckGoodsFile()
{
try
{
Windows.Storage.StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile storageFile = await storageFolder.GetFileAsync("Goods.xml");
}
catch(IOException e)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine(e.Message);
#endif
Windows.Storage.StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile storageFile = await storageFolder.CreateFileAsync("Goods.xml", CreationCollisionOption.ReplaceExisting);
XmlDocument doc = new XmlDocument();
XmlElement ele = doc.CreateElement("orders");
ele.InnerText = "";
doc.AppendChild(ele);
await doc.SaveToFileAsync(storageFile);
}
try
{
Windows.Storage.StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile storageFile = await storageFolder.GetFileAsync("ShoppingCart.xml");
}
catch (IOException e)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine(e.Message);
#endif
Windows.Storage.StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile storageFile = await storageFolder.CreateFileAsync("ShoppingCart.xml", CreationCollisionOption.ReplaceExisting);
XmlDocument doc = new XmlDocument();
XmlElement ele = doc.CreateElement("goods");
ele.InnerText = "";
doc.AppendChild(ele);
await doc.SaveToFileAsync(storageFile);
}
}
示例3: InitDataBase
/// <summary>
/// Init the Connector. Create the File if not exist, or open and load it.
/// </summary>
public async void InitDataBase()
{
var localFolder = ApplicationData.Current.LocalFolder;
_rootDocument = new XmlDocument();
_databaseXmlFile = await localFolder.CreateFileAsync("TaskTimeRecorder.xml", CreationCollisionOption.OpenIfExists);
var fileContent = await FileIO.ReadTextAsync(_databaseXmlFile);
if (fileContent == "")
{
var rootElement = _rootDocument.CreateElement("TaskTimeRecorder");
var tasksElement = _rootDocument.CreateElement("Tasks");
rootElement.AppendChild(tasksElement);
_rootDocument.AppendChild(rootElement);
_rootDocument.SaveToFileAsync(_databaseXmlFile);
}
else
{
_rootDocument.LoadXml(fileContent);
LoadAllTasks();
}
}
示例4: SaveAsync
public static async void SaveAsync(string filename, object obj)
{
/*
//this use the Local folder but can be other
var applicationData = ApplicationData.Current;
var storageFolder = applicationData.LocalFolder;
var file = await storageFolder.CreateFileAsync("User.xml", CreationCollisionOption.ReplaceExisting);
var dataContractSerializer = new DataContractSerializer(obj.GetType());
var memoryStream = new MemoryStream();
dataContractSerializer.WriteObject(memoryStream, obj);
memoryStream.Seek(0, SeekOrigin.Begin);
string serialized = new StreamReader(memoryStream).ReadToEnd();
memoryStream.Dispose();
var doc = new XmlDocument();
doc.LoadXml(serialized);
await doc.SaveToFileAsync(file);
*/
MessageDialog dialog;
// Declare Variables
StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile xmlFile = null;
try
{
xmlFile = await storageFolder.GetFileAsync("filePathList.xml");
}
catch (FileNotFoundException ex)
{
string message = ex.Message;
}
// If xml file doesn't exist, make it with initial setting
if (xmlFile == null)
{
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><files></files>";
var doc = new XmlDocument();
doc.LoadXml(xml);
// save xml to a file
xmlFile = await storageFolder.CreateFileAsync("filePathList.xml"
, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
await doc.SaveToFileAsync(xmlFile);
// Add permission to the files
StorageApplicationPermissions.FutureAccessList.Add(xmlFile);
}
// Make XmlDom and init variable with the file
XmlDocument xmlDoc = await XmlDocument.LoadFromFileAsync(xmlFile);
XmlElement root = xmlDoc.DocumentElement;
// Check duplicated name
XmlNodeList fileNodeList = root.GetElementsByTagName("file");
if (!(fileNodeList.Count() == 0))
{
foreach (XmlElement fileNode in fileNodeList)
{
string munoramaName = fileNode.GetAttribute("id");
if (filename.Equals(munoramaName))
{
// Create the message dialog and set its content
dialog = new Windows.UI.Popups.MessageDialog("이미 같은 이름의 파일이 있습니다. 다른 이름으로 만들어 주세요.");
dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
dialog.DefaultCommandIndex = 0;
dialog.CancelCommandIndex = 1;
await dialog.ShowAsync();
return;
}
}
}
// Get file element
XmlElement file = xmlDoc.CreateElement("file");
file.SetAttribute("id", filename);
// Get MyCanvas Element
XmlElement newcanvas = xmlDoc.CreateElement("canvas");
Canvas canvas_save = obj as Canvas;
var memoryStream = new MemoryStream();
UserDetail Stats = new UserDetail();
Type each_type;
while (canvas_save.Children.Count!=0) {
each_type = canvas_save.Children.First().GetType();
Stats.Type_of = each_type.ToString();
if (each_type == typeof(Line))
{
Line thisline = canvas_save.Children.First() as Line;
Stats.Points_X1 = thisline.X1;
Stats.Points_Y1 = thisline.Y1;
//.........這裏部分代碼省略.........
示例5: Save
// Write project to project xml file
public async void Save()
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("TranscriberProject");
root.SetAttribute("Name", Name);
XmlElement utterancesEl = doc.CreateElement("Utterances");
foreach (Utterance u in Utterances)
{
XmlElement utteranceEl = u.ToXmlElement(doc);
utterancesEl.AppendChild(utteranceEl);
}
root.AppendChild(utterancesEl);
doc.AppendChild(root);
await doc.SaveToFileAsync(ProjectFile);
foreach (Utterance u in Utterances)
{
u.Modified = false;
}
}
示例6: LoadLocalMetadata
private async Task LoadLocalMetadata()
{
if (localXml == null)
{
var file = await _folder.CreateFileAsync("magazines.metadata", CreationCollisionOption.OpenIfExists);
Task task = null;
try
{
localXml = await XmlDocument.LoadFromFileAsync(file);
}
catch
{
localXml = new XmlDocument();
var root = localXml.CreateElement("root");
localXml.AppendChild(root);
task = localXml.SaveToFileAsync(file).AsTask();
}
if (task != null)
await task;
}
_magazinesLocalUrl.Clear();
var mags = localXml.SelectNodes("/root/mag");
bool error = false;
foreach (var mag in mags)
{
try
{
_magazinesLocalUrl.Add(DownloadManager.GetLocalUrl(mag));
}
catch
{
error = true;
break;
}
}
if (error)
{
var file = await _folder.CreateFileAsync("magazines.metadata", CreationCollisionOption.ReplaceExisting);
localXml = new XmlDocument();
var root = localXml.CreateElement("root");
localXml.AppendChild(root);
var task = localXml.SaveToFileAsync(file).AsTask();
_magazinesLocalUrl.Clear();
}
if (_magazinesLocalUrl.Count == 0)
{
var fileHandle =
await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"CustomizationAssets\Magazines.plist");
var stream = await fileHandle.OpenReadAsync();
var dataReader = new DataReader(stream.GetInputStreamAt(0));
var size = await dataReader.LoadAsync((uint)stream.Size);
var str = dataReader.ReadString(size);
dataReader.DetachStream();
stream.Dispose();
stream = null;
if (str.Contains("<!DOCTYPE"))
{
var pos = str.IndexOf("<!DOCTYPE");
var end = str.IndexOf(">", pos + 7);
if (end >= 0)
str = str.Remove(pos, end - pos + 1);
}
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);
await ReadPList(xml);
var folder = ApplicationData.Current.LocalFolder;
try
{
// Set query options to create groups of files within result
var queryOptions = new QueryOptions(Windows.Storage.Search.CommonFolderQuery.DefaultQuery);
queryOptions.UserSearchFilter = "System.FileName:=Covers";
// Create query and retrieve result
StorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(queryOptions);
IReadOnlyList<StorageFolder> folders = await queryResult.GetFoldersAsync();
if (folders.Count != 1)
{
await Utils.Utils.LoadDefaultData();
}
}
catch { }
}
}
示例7: DownloadPDFAssetsAsync
private async Task<StorageFile> DownloadPDFAssetsAsync(LibrelioLocalUrl magUrl, IList<string> list, IProgress<int> progress = null, CancellationToken cancelToken = default(CancellationToken))
{
var folder = await StorageFolder.GetFolderFromPathAsync(magUrl.FolderPath.Substring(0, magUrl.FolderPath.Length-1));
var file = await folder.CreateFileAsync(magUrl.MetadataName, CreationCollisionOption.ReplaceExisting);
var xml = new XmlDocument();
var root = xml.CreateElement("root");
var name = xml.CreateElement("name");
name.InnerText = magUrl.FullName;
var date = xml.CreateElement("date");
date.InnerText = DateTime.Today.Month.ToString() + "/" + DateTime.Today.Day.ToString() + "/" + DateTime.Today.Year.ToString();
xml.AppendChild(root);
root.AppendChild(name);
root.AppendChild(date);
await xml.SaveToFileAsync(file);
cancelToken.ThrowIfCancellationRequested();
for (int i = 0; i < list.Count; i++)
{
var loader = new ResourceLoader();
StatusText = loader.GetString("downloading") + " " + (i + 2) + "/" + (list.Count + 1);
var url = list[i];
cancelToken.ThrowIfCancellationRequested();
string absLink = url;
var pos = absLink.IndexOf('?');
if (pos >= 0) absLink = url.Substring(0, pos);
string fileName = absLink.Replace("http://localhost/", "");
string linkString = "";
linkString = folder.Path + "\\" + absLink.Replace("http://localhost/", "");
pos = magUrl.Url.LastIndexOf('/');
var assetUrl = magUrl.Url.Substring(0, pos + 1);
absLink = absLink.Replace("http://localhost/", assetUrl);
var sampleFile = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await DownloadFileAsyncWithProgress(absLink, sampleFile, progress, cancelToken);
var asset = xml.CreateElement("asset");
asset.InnerText = linkString;
root.AppendChild(asset);
await xml.SaveToFileAsync(file);
}
return file;
}
示例8: LoadLocalMetadataDownloaded
private async Task LoadLocalMetadataDownloaded()
{
if (localDownloadedXml == null)
{
var file = await _folder.CreateFileAsync("magazines_downloaded.metadata", CreationCollisionOption.OpenIfExists);
Task task = null;
try
{
localDownloadedXml = await XmlDocument.LoadFromFileAsync(file);
}
catch
{
localDownloadedXml = new XmlDocument();
var root = localDownloadedXml.CreateElement("root");
localDownloadedXml.AppendChild(root);
task = localDownloadedXml.SaveToFileAsync(file).AsTask();
}
if (task != null)
await task;
}
_magazinesLocalUrlDownloaded.Clear();
var mags = localDownloadedXml.SelectNodes("/root/mag");
bool error = false;
foreach (var mag in mags)
{
try
{
_magazinesLocalUrlDownloaded.Add(DownloadManager.GetLocalUrl(mag));
}
catch
{
error = true;
break;
}
}
if (error)
{
var file = await _folder.CreateFileAsync("magazines_downloaded.metadata", CreationCollisionOption.ReplaceExisting);
localDownloadedXml = new XmlDocument();
var root = localDownloadedXml.CreateElement("root");
localDownloadedXml.AppendChild(root);
var task = localDownloadedXml.SaveToFileAsync(file).AsTask();
_magazinesLocalUrlDownloaded.Clear();
}
foreach (var item in _magazinesLocalUrlDownloaded)
{
var items = _magazinesLocalUrl.Where(magazine => magazine.FullName.Equals(item.FullName));
if (items != null && items.Count() > 0)
{
var magazine = items.First();
var index = _magazinesLocalUrl.IndexOf(magazine);
if (index == -1) continue;
_magazinesLocalUrl[index] = item;
}
}
}
示例9: SaveDatabase
public async void SaveDatabase(XmlDocument document)
{
var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Database");
var file = await folder.CreateFileAsync("database.xml", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await document.SaveToFileAsync(file);
}
示例10: save_click
async private void save_click(object sender, RoutedEventArgs e)
{
try
{
Windows.Storage.StorageFile file = null;
Windows.Storage.StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<profile/>");
XmlElement userNode = xmlDoc.CreateElement("username");
XmlElement emailNode = xmlDoc.CreateElement("email");
XmlElement phoneNode = xmlDoc.CreateElement("phone");
XmlCDataSection userName = xmlDoc.CreateCDataSection(input_username.Text);
XmlCDataSection email = xmlDoc.CreateCDataSection(input_email.Text);
XmlCDataSection phone = xmlDoc.CreateCDataSection(input_phone.Text);
userNode.AppendChild(userName);
emailNode.AppendChild(email);
phoneNode.AppendChild(phone);
xmlDoc.DocumentElement.AppendChild(userNode);
xmlDoc.DocumentElement.AppendChild(emailNode);
xmlDoc.DocumentElement.AppendChild(phoneNode);
bool createFile = false;
try
{
file = await local.GetFileAsync("profile.xml");
}
catch
{
createFile = true;
}
if(createFile)
{
file = await local.CreateFileAsync("profile.xml");
}
await xmlDoc.SaveToFileAsync(file);
}
catch { }
this.navigationHelper.GoBack();
}
示例11: Button_Click
async private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
//獲取記事本的文件夾對象NoteList
StorageFolder storage = await ApplicationData.Current.LocalFolder.GetFolderAsync("CityList");
//創建一個XML對象
XmlDocument _doc = new XmlDocument();
//使用記事本名字創建一個XML元素作為根節點
XmlElement _item = _doc.CreateElement(btn.Content.ToString());
//使用屬性來作為信息的標識符,使用屬性值來存儲相關的信息
//_item.SetAttribute("city", t.Text );
_doc.AppendChild(_item);
//創建一個應用文件
StorageFile file = await storage.CreateFileAsync(btn.Content.ToString() + ".xml", CreationCollisionOption.ReplaceExisting);
//把XML的信息保存到文件中去
await _doc.SaveToFileAsync(file);
(Window.Current.Content as Frame).Navigate(typeof(CollectionCity));
}
示例12: OnNavigatedTo
/// <summary>
/// 在此頁將要在 Frame 中顯示時進行調用。
/// </summary>
/// <param name="e">描述如何訪問此頁的事件數據。
/// 此參數通常用於配置頁。</param>
async protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter != null)
{
cityname = new Citys();
cityname.city = e.Parameter.ToString();
App.nearFindCity.Clear();
//讀取近期城市文件
StorageFolder storage = await ApplicationData.Current.LocalFolder.CreateFolderAsync("NearCityList", CreationCollisionOption.OpenIfExists);
//獲取當前文件夾中的文件
var files = await storage.GetFilesAsync();
//遍曆每個文件
foreach (StorageFile file in files)
{
file.DateCreated.ToFileTime();
//XmlDocument doc=await XmlDocument.LoadFromUriAsync (new Uri(file.Path));
//cityname.city = doc.DocumentElement.Attributes.GetNamedItem("city").NodeValue.ToString();
cityname1 = new Citys();
cityname1.city = file.DisplayName;
if (cityname1.city == "City")
continue;
else
{
App.nearFindCity.Add(cityname1);
}
}
if (App.nearFindCity.Count == 0)
App.nearFindCity.Add(cityname);
else
{
//if(App.nearFindCity.Contains (cityname )==true )
// return;
foreach (Citys city5 in App.nearFindCity)
{
if (city5.city.ToString() == cityname.city.ToString())
goto loop;
}
App.nearFindCity.Add(cityname);
if (App.nearFindCity.Count > 3)
{
do
{
Random r = new Random();
App.nearFindCity.RemoveAt(r.Next(2));
} while (App.nearFindCity.Count != 3);
}
}
loop:
StorageFolder storage1 = await ApplicationData.Current.LocalFolder.CreateFolderAsync("NearCityList",CreationCollisionOption.ReplaceExisting);
foreach(Citys cityname2 in App.nearFindCity )
{
XmlDocument _doc = new XmlDocument();
XmlElement _item = _doc.CreateElement(cityname2.city.ToString ());
_doc.AppendChild(_item);
StorageFile file1 = await storage1.CreateFileAsync(cityname2.city.ToString() + ".xml", CreationCollisionOption.ReplaceExisting);
await _doc.SaveToFileAsync(file1);
}
}
}
示例13: nextButton_Click_1
private async void nextButton_Click_1(object sender, RoutedEventArgs e)
{
if ("Exit".Equals(nextButton.Content.ToString()))
{
StorageFile st = null;
bool exists = true;
XmlNodeList _names = null, _scores = null;
try
{
st = await ApplicationData.Current.LocalFolder.GetFileAsync("score.xml");
dom = await XmlDocument.LoadFromFileAsync(st);
_names = dom.GetElementsByTagName("name");
_scores = dom.GetElementsByTagName("highscore");
}
catch (Exception)
{
exists = false;
}
if (!exists)
{
st = await ApplicationData.Current.LocalFolder.CreateFileAsync("score.xml");
}
ObservableCollection<Player> playerTable = new ObservableCollection<Player>();
if (_names != null)
{
for (int i = 0; i < _names.Count; i++)
{
string tempName = _names.ElementAt(i).InnerText;
int tempScore = Int32.Parse(_scores.ElementAt(i).InnerText);
playerTable.Add(new Player(tempName, tempScore));
}
}
playerTable.Add(new Player(playerName, score));
dom = new XmlDocument();
x = dom.CreateElement("users");
dom.AppendChild(x);
foreach (var elem in playerTable)
{
XmlElement x1 = dom.CreateElement("user");
XmlElement x11 = dom.CreateElement("name");
x11.InnerText = elem.Name;
x1.AppendChild(x11);
XmlElement x12 = dom.CreateElement("highscore");
x12.InnerText = elem.Score.ToString();
x1.AppendChild(x12);
x.AppendChild(x1);
}
await dom.SaveToFileAsync(st);
Frame.Navigate(typeof(MainPage));
}
else
{
var param = new Parameters();
param.Score = this.score + 10 + this.levelCount;
param.Name = this.playerName;
param.Level = this.levelCount + 1;
param.Counter = this.futureCounter;
Frame.Navigate(typeof(Level), param);
}
}
示例14: Button_Click
private async void Button_Click(object sender, RoutedEventArgs e)
{
StorageFile localFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("usersettings.xml", CreationCollisionOption.ReplaceExisting);
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("Categories");
xmlDoc.AppendChild(root);
foreach (Bill bill in selectedBills)
{
XmlElement xmlElement = xmlDoc.CreateElement("Bill");
xmlElement.SetAttribute("Type", bill.BillType.ToString());
xmlElement.SetAttribute("Title", bill.Title);
xmlElement.SetAttribute("SubTitle", bill.SubTitle);
xmlElement.SetAttribute("ImagePath", bill.ImagePath);
xmlElement.SetAttribute("PortalUrl", bill.PortalUrl);
XmlElement dueDate = xmlDoc.CreateElement("DueDate");
dueDate.InnerText = bill.DueDate.ToString();
XmlElement isPaid = xmlDoc.CreateElement("IsPaid");
isPaid.InnerText = bill.IsPaid.ToString();
xmlElement.AppendChild(dueDate);
xmlElement.AppendChild(isPaid);
root.AppendChild(xmlElement);
}
await xmlDoc.SaveToFileAsync(localFile);
this.Frame.Navigate(typeof(HomePage));
}
示例15: LoadSettingsAsync
/// <summary>
/// Loads stored settings, instantiates FaceServiceClient, and generates a GUID for FaceList if one didn't previously exist.
/// </summary>
private static async Task LoadSettingsAsync()
{
_faceClient = new FaceServiceClient(((App)Application.Current).AppSettings.FaceApiKey);
if (await ApplicationData.Current.LocalFolder.TryGetItemAsync("FaceSettings.xml") != null)
{
StorageFile SettingsInfo = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/FaceSettings.xml"));
var SettingsDocument = await XmlDocument.LoadFromFileAsync(SettingsInfo);
_listKey = SettingsDocument.GetElementsByTagName("ListKey").FirstOrDefault<IXmlNode>().Attributes.GetNamedItem("Key").InnerText;
if (_listKey == "")
{
_listKey = Guid.NewGuid().ToString();
await SaveSettingsAsync();
}
}
else
{
XmlDocument SettingsDocument = new XmlDocument();
var DefaultXml = "<FacialVerificationSettings>\n" +
"\t<ListKey Key =\"\"/>\n" +
"</FacialVerificationSettings>\n";
SettingsDocument.LoadXml(DefaultXml);
_listKey = Guid.NewGuid().ToString();
SettingsDocument.GetElementsByTagName("ListKey").FirstOrDefault<IXmlNode>().Attributes.GetNamedItem("Key").InnerText = _listKey;
StorageFile SettingsInfo = await ApplicationData.Current.LocalFolder.CreateFileAsync("FaceSettings.xml");
await SettingsDocument.SaveToFileAsync(SettingsInfo);
}
}