Как отобразить значение в файле журнала из XML-файла - PullRequest
0 голосов
/ 17 сентября 2009

У меня есть xml-файл sample.xml, расположенный в некоторой папке:

<?xml version="1.0"?>
<!-- Please Enter your frequency value between 10sec to 80sec --> 
<Time>
  <Value>80</Value>
</Time>

этот xml-файл выдается пользователю, если кто-либо входит за пределы, скажем, 8, или 700 он отправит значение по умолчанию как 80 в файле журнала (это Windowservice, у нас нет никакого пользовательского интерфейса), в противном случае, что бы ни потребовалось для данного для отображения если это строка или алфавитно-цифровая, она отправит сообщение об ошибке в файл журнала.

Мне нужна кодировка c # в блоке try, catch для отображения этих вещей в лог-файлах

Это место означает, что функция, которую они ранее выполняли, означает, что здесь зафиксировано значение, когда нет файлов xml, какой (файл xml) нам нужно использовать сейчас.

public sampleInterface()
{
    // This call is required by the Windows.Forms Component Designer.
    InitializeComponent();
    // 
    // NetIqInterface
    // ## Heading ##
    this.CanHandlePowerEvent = false;
    this.CanPauseAndContinue = true;
    this.CanShutdown = false;

    //
    // Initialize static variables
    //
    etl = new EtlDebug( ProjectInstaller.SERVICE_NAME, "netiq", "NIQTRACES" );

    if (outstandingTimers == null) outstandingTimers = new ArrayOfTimers();

    //
    // Initialize polling timer - set to 80 seconds for now.
    //
    LeafDebug.DebugTraceNormal( "InitializeComponent", "Set polling timer: 60000ms" );
    timer = new System.Timers.Timer( 60000 );
    timer.Elapsed += new ElapsedEventHandler( OnTimer );

    // The method in the Leaf.Resources instantiates the resource
    // manager appropriately to access the resource file.
    resources = Managers.LeafStrings;
}

Ответы [ 2 ]

0 голосов
/ 18 сентября 2009

Это код, который я сделал для этой функции

попытка { string xmlFilePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString () + "NetIQ.xml"; FileInfo checkFile = new FileInfo (xmlFilePath); if (checkFile.Exists) { // Правда readVal = ReadValFromXML (xmlFilePath);

               if (!(readVal > 10 && readVal <= 600))
               {
                   LeafDebug.DebugTraceNormal("InitializeComponent", "timer: 60sec");
                   readVal = 60000;
               }
               else
               {

                   this.readVal = this.readVal * 1000;
                   LeafDebug.DebugTraceNormal("Modified interval is accepted.", "Set  timer to: " + (this.readVal / 1000) + ".");
               }
           }
           else
           { // False
               LeafDebug.DebugTraceNormal("InitializeComponent", "Set polling timer: 60sec");
               readVal = 60000;
           }
           PassToTimer(readVal);
       }
       catch (Exception ex)
       {

           LeafDebug.DebugTraceSevere("The Error Occured in  file.", ex.ToString());
           LeafDebug.DebugTraceSevere(" Interval Error.", " interval value is not in correct format /  file not found.");
           LeafDebug.DebugTraceNormal("InitializeComponent", "Set  timer: 60sec");
           readVal = 60000;
           PassToTimer(readVal);
       }


/// <summary>
   /// PassToTimer(int readVal): This function will pass the readVal to Timer
   /// </summary>
   /// <param name="readVal"></param>
   private void PassToTimer(int readVal)
   {
       timer = new System.Timers.Timer(readVal);
       timer.Elapsed += new ElapsedEventHandler(OnTimer);
       // The method in the Leaf.Resources instantiates the resource
       // manager appropriately to access the resource file.
       resources = Managers.LeafStrings;
   }

  /// <summary>
   /// ReadValFromXML(string path) : This Method will Read and returns the Pooling interval Value from NetIQPollingInterval.xml.
   /// </summary>
   /// <param name="path"> path determines the working directory of the application</param>
   /// <returns> Returns Pooling interval Value </returns>
   /// <creator> Created by Faishal </creator>
   /// <Date> 24th Aug '09 </Date>
   /// <ReasonForCreation> User can enter the Pooling Interval time by Modifying the value of file </ReasonForCreation>
   /// <xmlFileLocation> Project Folder </xmlFileLocation>
   private Int32 ReadValFromXML(string path)
   {
       XmlDocument xmlDoc = new XmlDocument();
       xmlDoc.Load(path);
       XmlNode node = xmlDoc.SelectSingleNode("Time");
       Int32 val = Int32.Parse(node.FirstChild.InnerText.ToString());
       return val;
   }
0 голосов
/ 17 сентября 2009

Было бы проще использовать файл app.config вместо отдельного файла XML. Затем вы можете использовать встроенные классы для чтения значений. Вот пример.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...