如何使用文件观察器服务解析XML。 [英] How can I parse XML using file watcher services.

查看:67
本文介绍了如何使用文件观察器服务解析XML。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用C#FileWatcher服务解析一个XML文件。我是Windows Services的新手。我尝试过一个简单的Web服务,但它工作不正常。有人可以帮忙解决这个问题,因为这很紧急。在此先感谢。



我尝试过:



I need to parse one XML file using C# FileWatcher services. I am new to Windows Services. I have tried one simple web service but its not working fine. Can someone please help regarding this as this is urgent. Thanks in advance.

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Threading;

namespace FileWatcherWinService
{
    public partial class FileWatcherService : ServiceBase
    {
        string WatchPath1 = ConfigurationManager.AppSettings["WatchPath1"];
        string WatchPath2 = ConfigurationManager.AppSettings["WatchPath2"];
        public FileWatcherService()
        {
            InitializeComponent();
            fileWatcherWatchDdriveArticleimagefolder.Created += fileWatcherWatchDdriveArticleimagefolder_Created;
            fileWatcherWatchDDriveMYdataFolder.Created += fileWatcherWatchDDriveMYdataFolder_Created;
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Thread.Sleep(15000);
                fileWatcherWatchDdriveArticleimagefolder.Path = WatchPath1;
                fileWatcherWatchDDriveMYdataFolder.Path = WatchPath2;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
       

        protected override void OnStop()
        {
            try
            {
                Create_ServiceStoptextfile();
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }


        /// <summary>
        /// This event monitor folder wheater file created or not.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void fileWatcherWatchDDriveMYdataFolder_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            try
            {
                Thread.Sleep(70000);
                //Then we need to check file is exist or not which is created.
                if (CheckFileExistance(WatchPath2, e.Name))
                {
                    //Then write code for log detail of file in text file.
                    CreateTextFile(WatchPath2,e.Name);
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        /// <summary>
        /// This event monitor folder wheater file created or not.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void fileWatcherWatchDdriveArticleimagefolder_Created(object sender, System.IO.FileSystemEventArgs e)
        {


            try
            {
                Thread.Sleep(70000);
                //Then we need to check file is exist or not which is created.
                if (CheckFileExistance(WatchPath1, e.Name))
                {
                    //Then write code for log detail of file in text file.
                    CreateTextFile(WatchPath1, e.Name);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }


        }
        #region Method
        private bool CheckFileExistance(string FullPath, string FileName)
        {
            // Get the subdirectories for the specified directory.'
            bool IsFileExist = false;
            DirectoryInfo dir = new DirectoryInfo(FullPath);
            if (!dir.Exists)
                IsFileExist = false;
            else
            {
                string FileFullPath = Path.Combine(FullPath, FileName);
                if (File.Exists(FileFullPath))
                    IsFileExist = true;
            }
            return IsFileExist;


        }
        private void CreateTextFile(string FullPath, string FileName)
        {
            StreamWriter SW;
            if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))
            {
                SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("yyyyMMdd") + ".txt"));
                SW.Close();
            }
            using (SW = File.AppendText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))
            {
                SW.WriteLine("File Created with Name: " + FileName + " at this location: " + FullPath);
                SW.Close();
            }
        }
        public static void Create_ServiceStoptextfile()
        {
            string Destination = "C:/Users/jhana/Desktop/FileWatcherFiles/ServiceStopTime";
            StreamWriter SW;
            if (Directory.Exists(Destination))
            {
                Destination = System.IO.Path.Combine(Destination, "txtServiceStop_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!File.Exists(Destination))
                {
                    SW = File.CreateText(Destination);
                    SW.Close();
                }
            }
            using (SW = File.AppendText(Destination))
            {
                SW.Write("\r\n\n");
                SW.WriteLine("Service Stopped at: " + DateTime.Now.ToString("dd-MM-yyyy H:mm:ss"));
                SW.Close();
            }
        }
        #endregion Method
    }
}

推荐答案

解析XML的一种简单方法是使用LINQ to XML。添加对System.Xml.Linq.dll的引用,并使用System.Xml.Linq; 将添加到您的代码文件中。



您可以像这样使用它:

A simple way to parse XML is to use LINQ to XML. Add a reference to System.Xml.Linq.dll and add using System.Xml.Linq; to your code file.

You can use it like this:
var doc = XDocument.Load("file.xml");

// finding elements: example
var elements = doc.Root.Descendants("elementName");

// only selecting elements with a specific attribute: example
var selected = elements.Where(x => x.Attribute("name") == "value");

// getting content from these elements: example
var values = selected.Select(x => x.Value);

foreach (string v in values)
{
    // do something with 'v'
}



这只是一个例子;我不知道你需要解析什么。使用以下文档了解有关LINQ to XML的更多信息:

LINQ to XML( C#) [ ^ ]

XDocument Class( System.Xml.Linq) [ ^ ]



如果你想要LINQ方法,你也可以使用 System.Xml.XmlDocument System.Xml.XmlReader 。在我看来,LINQ to XML代码仍然是最容易读写的。

XmlDocument类(System.Xml) [ ^ ]

XmlReader类(System.Xml) [ ^ ]


That is just an example; I don't know what exactly you need to parse. Learn a bit more about LINQ to XML using the docs:
LINQ to XML (C#)[^]
XDocument Class (System.Xml.Linq)[^]

If you do not want the LINQ approach, you can also use System.Xml.XmlDocument or System.Xml.XmlReader. LINQ to XML code is still the easiest to read and write though, in my opinion.
XmlDocument Class (System.Xml)[^]
XmlReader Class (System.Xml)[^]


这篇关于如何使用文件观察器服务解析XML。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆