加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

WinRT StorageFile 读写操作xml

发布时间:2020-12-15 22:51:57 所属栏目:百科 来源:网络整理
导读:using System;using System.Linq;using System.Reflection;using System.Threading.Tasks;using Windows.Data.Xml.Dom;using Windows.Storage;namespace Microsoft.Assistant.MobileAssistantRT.Utilities{ public class LocalFolderHelper { private const
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Storage;

namespace Microsoft.Assistant.MobileAssistantRT.Utilities
{
    public class LocalFolderHelper
    {
        private const string STORE_CONFIG_NAME = "Config.xml";
        private const string STORE_CONFIG_FOLDERNAME = "Data";
        private static StorageFolder localFolder = ApplicationData.Current.LocalFolder;

        /// <summary>
        /// Create the storeConfig.xml if it need.
        /// </summary>
        /// <typeparam name="T">the Generics type</typeparam>
        /// <param name="t">the type to save</param>
        public async static Task CreateStoreConifgXML<T>(T t)
        {
            StorageFolder storageFolder = await localFolder.CreateFolderAsync(STORE_CONFIG_FOLDERNAME,CreationCollisionOption.OpenIfExists);
            StorageFile storageFile = await storageFolder.CreateFileAsync(STORE_CONFIG_NAME,CreationCollisionOption.ReplaceExisting);
            var properties = t.GetType().GetTypeInfo().DeclaredProperties;
            XmlDocument dom = new XmlDocument();
            XmlElement xmlRootNode;

            xmlRootNode = dom.CreateElement("Configuration");
            dom.AppendChild(xmlRootNode);

            XmlElement x1 = dom.CreateElement(t.GetType().Name);

            foreach (var property in properties)
            {
                XmlElement xmlElement = dom.CreateElement(property.Name);

                if (property.GetValue(t) != null)
                {
                    xmlElement.InnerText = property.GetValue(t).ToString();
                }
                x1.AppendChild(xmlElement);
            }
            xmlRootNode.AppendChild(x1);

            await dom.SaveToFileAsync(storageFile);
        }

        /// <summary>
        /// Check whether the storeConfig.xml exists. 
        /// path: C:UsersUserNameAppDataLocalPackagespackageNameLocalStateDataConfig.xml
        /// </summary>
        /// <returns>return null if not exists.</returns>
        public async static Task<StorageFile> CheckStoreConfigExist()
        {
            try
            {
                StorageFolder folderFound = await localFolder.GetFolderAsync(STORE_CONFIG_FOLDERNAME);
                StorageFile fileFound = await folderFound.GetFileAsync(STORE_CONFIG_NAME);

                return fileFound;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// Read config from xml
        /// </summary>
        /// <typeparam name="T">The type to return</typeparam>
        /// <param name="storageFile">the data source</param>
        /// <param name="t">the object</param>
        /// <returns></returns>
        public async static Task<T> GetDataFromConifgXML<T>(StorageFile storageFile,T t)
        {
            if (storageFile == null)
            {
                return default(T);
            }

            var stream = await storageFile.OpenAsync(FileAccessMode.Read);
            XmlDocument xmlDoc = await XmlDocument.LoadFromFileAsync(storageFile);
            XmlNodeList nodes = xmlDoc.SelectNodes(@"/Configuration/" + t.GetType().Name);
            IXmlNode node = nodes.FirstOrDefault();
            if (node == null)
            {
                return default(T);
            }
            var properties = t.GetType().GetTypeInfo().DeclaredProperties;

            if (node != null && node.HasChildNodes())
            {
                var list = node.ChildNodes;
                foreach (var item in list)
                {
                    PropertyInfo prop = properties.Where((i) => i.Name.Equals(item.LocalName)).FirstOrDefault();
                    if (prop != null)
                    {
                        int newInt;
                        Guid newGuid = Guid.Empty;
                        if (prop.PropertyType.Name.Equals("Int32") && Int32.TryParse(item.InnerText,out newInt))
                        {
                            prop.SetValue(t,newInt);
                        }
                        // some property maybe nullable.
                        else if (prop.PropertyType.FullName.Contains("Guid") && Guid.TryParse(item.InnerText,out newGuid))
                        {
                            prop.SetValue(t,newGuid);
                        }
                        else
                        {
                            prop.SetValue(t,item.InnerText);
                        }
                    }
                }

            }

            return (T)t;
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读