簡體   English   中英

C#申請批處理文件

[英]C# Application to batch file

我需要一點幫助,希望你們中的一個能幫助我。

我有一個路徑(目錄),其中有很多文件夾。在這些文件夾中,有很多我不知道的子文件夾和文件。 因此,我不知道它們和文件下有多少個子文件夾和子文件夾。 這是一棵大樹的文件夾。 我的任務是創建一個腳本,該腳本可以檢查是否存在72小時的文件夾或文件,如果存在,則需要刪除該文件夾。 這意味着我有很多文件夾。

一個示例是名為ANSYS的文件夾。 在ANSYS中,有許多子文件夾和文件。 我必須檢查所有ANSYS文件夾,並查看該文件夾及其子文件夾中的任何文件是否存在72個小時。 如果ANSYS中的所有內容都存在72小時,則必須刪除整個ANSYS。 我已經制作了一個可以完成我的工作的C#應用​​程序,但是我需要在數百台服務器上使用該應用程序,而且我沒有時間在所有服務器上安裝.NET框架。 這就是為什么我必須使用可以執行相同操作的bash腳本的原因。

這是我的C#應用​​程序,您可以查看它以了解更多我的作業:

using System;
using System.IO;

namespace Scripts
{
internal class Program
{
    private static void Main(string[] args)
    {
        //Defines the main path.
        var topPath = @"C:\Ansys_RSM_Work_DIR\";

        //Converts the first argument written as a parameter in TaskScheduler or CMD,       called 'hours'.
        string argument = args[0];
        int hours = Int32.Parse(argument);

        //Defines the timespan in which a file has to be modified. 
        var deleteIfNotModifiedIn = new TimeSpan(hours, 0, 0);

        //Is set to true if the file file has been modified within the timespan.
        bool fileTooOld = false;

        //Searches through all directories in topPath, one at a time.
        foreach (var dir in Directory.GetDirectories(topPath))
        {
            //Searches through all files in directory, one at a time.
            foreach (var file in Directory.GetFiles(dir, "*", SearchOption.AllDirectories))
            {
                //Calculate the difference between now and lastWriteTime = fileLastModified.
                var fileLastModified = DateTime.Now - File.GetLastWriteTime(file);
                if (fileLastModified < deleteIfNotModifiedIn)
                    fileTooOld = true;
            }
            if (fileTooOld == false)
                Directory.Delete(dir, true);
            else
                fileTooOld = false;
        }
    }
}
}

我已經嘗試制作腳本,但是如果腳本中的文件已存在72個小時,那么我編寫的腳本會刪除該子文件夾,這是不應該的。 如果自上一個72小時以來未修改ANSYS中的所有文件和ANSYS中的所有子文件夾,則它僅應刪除第一個文件夾(類似於ANSYS):我的腳本:

FORFILES /S /D -3 /C "cmd /c IF @isdir==TRUE rd /S /Q @path" 
for /f "delims=" %i in ('dir /s /b /ad ^| sort /r') do rd "%i"

誰能幫幫我嗎?

誠摯的問候Shaban Mahmood

好的,嘗試這樣的事情:

程序蝙蝠

@echo off
pushd  C\...[Taret folder containg folders to check, that is containing ANSYS]

set /p check="Date after which to check: "
Rem When prompted with above line type the date 3 days ago.

forfiles /c "cmd /c (IF @isdir==TRUE search "@path" "%check%")"
popd

並在同一目錄中:

Search.bat

set del=TRUE
forfiles /p %1 /d +%2 /s /m *.* /c "cmd /c (set del=FALSE)"
Pause |Echo Deleting %1... Exit to cancel
if %del%==True (rd /s %1)

應該可以,請注意,它將在刪除每個文件之前暫停。 它的工作方式是檢查與該文件一起發送的文件是否少於72小時,如果有,則不會刪除該文件夾。 它將對指定文件夾中的每個文件夾執行此操作。 search.bat文件是可以使用文件夾路徑調用的文件,它將根據您指定的要求搜索該父文件夾內的所有文件。 Program.bat為您完成了第一步。

如果出現故障(或根本無法工作),我將其暫停,如果是這種情況,請告訴我在哪里無效。 另外,如果需要解釋,請評論。

莫娜

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM