使用C#根据文本文件中的行进行决策

时间:2015-06-24 20:50:38

标签: c# batch-file

我需要编写一个可以由计划任务调用的C#控制台应用程序。我需要做的是比较两个 日期的文本文件。一个文件的日期比另一个文件的日期多。应用程序需要将日期列表与当前日期进行比较,并根据日期运行批处理文件。

如果文件A中的日期等于今天的日期,则查看文件B以查看今天的日期是否包含在文件B中。 如果它在文件B中,则运行批处理文件“B”。如果今天的日期未在文件B中列出,但在文件A中,则运行批处理文件“A”。如果今天的日期没有列在任何文本文件中,则不执行任何操作。

举个例子: 文件A的日期为, 1/1/2015 2015年1月8日 2015年1月15日 2015年1月22日 2015年1月29日

文件B的日期为, 2015年1月15日 2015年2月15日 2015年3月15日

我们假设今天是2015年1月15日。应用程序检查文件A并看到今天的日期存在。然后继续检查 文件B并发现今天的日期退出,因此它运行批处理文件“B”。如果今天的日期不在文件B中,它将运行批处理文件“A”。

如果今天是2015年1月31日,那么两者都不会成立,并且不会运行任何批处理文件。

这是我到目前为止所拥有的。 Fyi ......我是C#的新手,也是编程的新手。提前感谢您的任何帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;

namespace Automate_Script
{
    class Program
    {
        // get today's date
        private static DateTime today = DateTime.Today;

        // create the string arrays to hold the dates from the text files.     Initialize to null.
        private static string[] dateLinesWeek = null;
        private static string[] dateLinesMonth = null;

        static void Main(string[] args)
        {
            // display today's date in console window.
            Console.WriteLine("\n\t\tToday is {0}", today.ToString("d"));

            // attempts to read the 'weekDates' text file.
            try
            {
                // this is the text file that contains the dates for week-end run dates.
                dateLinesWeek = File.ReadAllLines(@"C:\MyScripts\weekDates.txt");
                dateLinesMonth = File.ReadAllLines(@"C:\MyScripts\monthDates.txt");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // create the process to run the batch execution.
            Process p = new Process();

            // iterate through the 'weekDates' text file
            foreach (var weekLine in dateLinesWeek)
            {
                if (Convert.ToDateTime(weekLine) == today)
                {
                    foreach (var monthLine in dateLinesMonth)
                    {
                        if (Convert.ToDateTime(monthLine) == today && Convert.ToDateTime(weekLine) == today)
                        {
                            try
                            {
                                string targetDirectory;
                                targetDirectory = string.Format(@"C:\MyScripts");

                                p.StartInfo.UseShellExecute = true;
                                p.StartInfo.WorkingDirectory = targetDirectory;
                                p.StartInfo.FileName = "monthTest.bat";
                                p.StartInfo.CreateNoWindow = false;
                                p.Start();
                                p.WaitForExit();
                                System.Threading.Thread.Sleep(3000);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Exception Occurred: {0}, {1}", ex.Message, ex.StackTrace.ToString());
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                else
                {
                    try
                    {
                        string targetDirectory;
                        targetDirectory = string.Format(@"C:\MyScripts");

                        p.StartInfo.UseShellExecute = true;
                        p.StartInfo.WorkingDirectory = targetDirectory;
                        p.StartInfo.FileName = "weekTest.bat";
                        p.StartInfo.CreateNoWindow = false;
                        p.Start();
                        p.WaitForExit();
                        System.Threading.Thread.Sleep(3000);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception Occurred: {0}, {1}", ex.Message, ex.StackTrace.ToString());
                    }
                    break;
                }
            }

            Console.ReadLine();
            //System.Threading.Thread.Sleep(3000);
        }
    }
}

我尝试了很多种上述代码,结果大致相同。我通常只能运行每周脚本。

4 个答案:

答案 0 :(得分:1)

我认为您的代码无法正常工作的原因是

else 
{
    return;
}

如果今天的日期不在月份文件的第一行,则应用程序将退出。

如果我理解你的要求,你将执行:

  • 脚本A.bat如果今天的日期出现在文件A.txt。
  • 如果今天的日期出现在文件A.txt和B.txt。
  • 中,则为脚本B.bat

如果是这样,我会做类似下面的事情。如果我误解了您的要求,您可能想要更改运行什么脚本的条件。

namespace Automate_Script
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime today =  DateTime.Today;
            // display today's date in console window.
            Console.WriteLine("\n\t\tToday is {0}", today.ToString("d"));

            if (!FileContainsDate(@"C:\MyScripts\weekDates.txt", today))
                return; // Todays date not present in week dates, nothing shall be done.

            if (FileContainsDate(@"C:\MyScripts\monthDates.txt", today))
            {
                RunScript("monthTest.bat");
            }
            else
            {
                RunScript("weekTest.bat");
            }

            Console.ReadLine();
        }

        private static bool FileContainsDate(string dateFile, DateTime date)
        {
            try
            {
                string[] dates = File.ReadAllLines(dateFile);
                return dates.Any(line => Convert.ToDateTime(line) == date);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false; 
            }
        }

        private static void RunScript(string scriptFile)
        {
            try
            {
                Process p = new Process();
                p.StartInfo.UseShellExecute = true;
                p.StartInfo.WorkingDirectory = @"C:\MyScripts";
                p.StartInfo.FileName = scriptFile;
                p.StartInfo.CreateNoWindow = false;
                p.Start();
                p.WaitForExit();
                System.Threading.Thread.Sleep(3000);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred: {0}, {1}", ex.Message, ex.StackTrace.ToString());
            }
        }
    }
}

答案 1 :(得分:0)

首先,我会描述您的场景有点不同:如果当前日期在文件B中,则执行monthTest.bat。如果没有,请检查它是否在文件A中,然后执行weekTest.bat。如果它不在任何一个中,则什么也不做。

您可以使用LINQ查询数组是否存在您的日期:

var fileToRun = string.Empty;
if (dateLinesMonth.Any(x => Convert.ToDateTime(x) == today)
{
    fileToRun = "monthTest.bat";
}
else if (dateLinesWeek.Any(x => Convert.ToDateTime(x) == today)
{
    fileToRun = "weekTest.bat";
}

if (!string.IsNullOrEmpty(fileToRun)) 
{
    // create and run process
}

答案 2 :(得分:0)

好的所以我认真简化了你所拥有的东西,并将你的字符串数组转换为列表。我也删除了你从文件中读取的内容,因为我不想在dotfiddle中使用它。这是另一种方法。

您可以在dotfiddle上看到以下代码。 https://dotnetfiddle.net/QYjoqw

public static void Main()
{
    var today = "1/8/2015";

    // create the string arrays to hold the dates from the text files.     Initialize to null.
    List<string> dateLinesWeek = null;
    List<string> dateLinesMonth = null;

    // this is the text file that contains the dates for week-end run dates.
    dateLinesWeek = new List<string>() {
        "1/1/2015", 
        "1/8/2015", 
        "1/15/2015", 
        "1/22/2015", 
        "1/29/2015"
    };
    dateLinesMonth= new List<string>() 
    {
        "1/15/2015", 
        "2/15/2015", 
        "3/15/2015"
    };

    if (dateLinesMonth.Contains(today))
    {
        Console.WriteLine("Execute B");
    }
    else if(dateLinesWeek.Contains(today))
    {
        Console.WriteLine("Execute A");
    }

答案 3 :(得分:0)

您在此问题中选择了batch-file标记,因此我发布了批处理文件解决方案(比C#解决方案简单得多)。

@echo off
setlocal

rem Get today's date and eliminate left zeros in each part
set today=%date:/0=/%

rem If there's a date in file A that's equal to today's date...
findstr /L "%today%" A.txt > NUL
if not errorlevel 1 (

   rem then look at file B to see if today's date is contained in file B.
   findstr /L "%today%" B.txt > NUL

   rem If it is in file B...
   if not errorlevel 1 (
      rem run batch file "B"
      call B.bat
   ) else (
      rem run batch file "A"
      call A.bat
   )

)

rem If today's date is not listed in file A, do nothing