簡體   English   中英

如何修復我的代碼以將已存在的文件移動到另一個目錄?

[英]How can I fix my code to move files that already exist to another directory?

這是我的第一個 C# 腳本,也是第一個基於非 SQL 的腳本。我真的為此感到自豪(如果沒有這個社區的幫助,我不可能這么快完成,謝謝!),但我知道它會各種亂七八糟。

該腳本遍歷單個目錄中的所有文件,從文件名中刪除特殊字符,並將文件重命名為標准的、用戶友好的名稱。 該腳本正在目錄中尋找一組特定的文件。 如果它發現一個不應該在目錄中的文件,它會將文件移動到一個安全文件夾並重命名它。 如果文件夾

我正在處理 4 個具有動態名稱的文件,這些文件將包括數字和特殊字符。 重命名過程分兩步進行:

  1. 從名稱中刪除特殊字符和數字。 例如:從“EOY 12.21.2018 - 12.28.2018 PRF.xls”到“EOYPRF.xls”

  2. 重命名文件以清楚地標記文件是什么。 例如:從“EOYPRF.xls”到“EOY_CompanyName.xls”

可能有文件意外添加到此目錄中,由於它們是工資單文件,因此它們是高度機密的,除非需要移動,否則不能移動(僅當它們是 4 個文件之一時),因此我將它們移動到文件存儲在同一目錄中的子目錄並重命名它們。

我還試圖說明我的腳本或流程是否在中途搞砸了。 此腳本是在 SSIS 中運行的更大自動化過程的一部分,因此存在許多故障點。 腳本可能會失敗並在目錄中留下 4 個文件中的一個或全部。 如果是這種情況,我需要在用戶添加要處理的新的、未更改的主文件之前將文件移出主目錄。 如果目錄包含具有相同最終名稱(“EOY_CompanyName.xls”)的文件,則它將無法正常工作。

我正在通過將三個場景放在目錄中來測試腳本。

  1. 2 個文件與 4 個主文件沒有任何關聯。
  2. 4 個未更改的主文件,格式為數字和特殊字符:“EOY 12.21.2018 - 12.28.2018 PRF.xls”
  3. 4 個已處於最終狀態的主文件(在將文件移動到最終目錄之前模擬故障)。 例如:“EOY_CompanyName.xls”

我面臨的問題是在極少數情況下,目錄中同時存在未更改的主文件和最終主文件,腳本一直運行到第一個未更改的文件,刪除特殊字符,然后在最終重命名步驟中失敗,因為文件已存在同名(上述 3 點中的場景 3)。 然后它將繼續運行腳本並將主文件之一移動到意外的文件目錄中,並出於某種原因停止處理任何其他文件。 我真的需要有經驗的人的幫助。

我已經嘗試了很多東西,但我認為這是處理文件的順序問題。 我有兩個名為“a.xls”和“b.xls”的文件,它們是意外文件的占位符。 它們是目錄中的前兩個文件,並且總是首先被處理。 目錄中的第三個文件是上面以未更改形式命名的文件(“EOY 12.21.2018 - 12.28.2018 PRF.xls”)。 它被重命名並移動到意外的文件夾中,但實際上應該傳遞它以將包含最終名稱(“EOY_CompanyName.xls”)的主文件移動到意外的文件夾中。 我想確保腳本在運行時只處理新文件,因此我想將所有無法通過腳本移動的已處理文件移動到另一個目錄中。

public void Main()
    {
        ///Define paths and vars
        string fileDirectory_Source = Dts.Variables["User::PayrollSourceFilePath"].Value.ToString();
        string fileDirectory_Dest = Dts.Variables["User::PayrollDestFilePath"].Value.ToString();
        string errorText = Dts.Variables["User::errorText"].Value.ToString();
        DirectoryInfo dirInfo_Source = new DirectoryInfo(fileDirectory_Source);
        DirectoryInfo dirInfo_Dest = new DirectoryInfo(fileDirectory_Dest);
        string finalFileName = "";

        List<string> files = new List<string>(new string[]
            {
            fileDirectory_Source + "EOY_PRF.xls",
            fileDirectory_Source + "EOY_SU.xls",
            fileDirectory_Source + "FS_PRF.xls",
            fileDirectory_Source + "FS_SU.xls"
            });

        Dictionary<string, string> fileNameChanges = new Dictionary<string, string>();
            fileNameChanges.Add("EOYReportPRF.xls", "EOY_PRF.xls");
            fileNameChanges.Add("PayrollEOY.xls", "EOY_SU.xls");
            fileNameChanges.Add("PRFFundingStatement.xls", "FS_PRF.xls");
            fileNameChanges.Add("SUFundingStatement.xls", "FS_SU.xls");

        ///Determine if all files present
        int count = dirInfo_Source.GetFiles().Length;
        int i = 0;

        ///Loop through directory to standardize file names
        try
        {
            foreach (FileInfo fi in dirInfo_Source.EnumerateFiles())
            {

                string cleanFileName = Regex.Replace(Path.GetFileNameWithoutExtension(fi.Name), "[0-9]|[.,/ -]", "").TrimEnd() + fi.Extension;
                File.Move(fileDirectory_Source + Path.GetFileName(fi.Name), fileDirectory_Source + cleanFileName);
                ///Move unexpectd files in source directory
                if (!fileNameChanges.ContainsKey(cleanFileName))
                    {
                        errorText = errorText + "Unexpected File: " + cleanFileName.ToString() + " moved into the Unexpected File folder.\r\n";

                        File.Move(dirInfo_Source + cleanFileName, dirInfo_Source + "Unexpected Files\\" + Path.GetFileNameWithoutExtension(cleanFileName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + fi.Extension);

                }
                if (fileNameChanges.ContainsKey(cleanFileName))
                    {
                        ///Final Friendly File Name from Dict
                        var friendlyName = fileNameChanges[cleanFileName];
                        ///Handle errors produced by files that already exist
                        if (files.Contains(fileDirectory_Source + friendlyName))//File.Exists(fileDirectory_Source + friendlyName))
                            {
                                MessageBox.Show("File.Exists(dirInfo_Source + friendlyName)" + File.Exists(dirInfo_Source + friendlyName).ToString() + "   cleanFileName   " + cleanFileName);
                                errorText = errorText + "File already exists: " + friendlyName.ToString() + " moved into the Unexpected File folder.\r\n";
                                File.Move(dirInfo_Source + friendlyName, dirInfo_Source + "Unexpected Files\\" + Path.GetFileNameWithoutExtension(friendlyName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(friendlyName));
                                return;
                            }
                        ///Rename files to friendly name
                        File.Move(dirInfo_Source + cleanFileName, dirInfo_Source + friendlyName);
                        finalFileName = friendlyName.ToString();
                    }
                ///Count valid PR files
                if (files.Contains(dirInfo_Source + finalFileName))
                    {
                    i++;
                    }
            }
            ///Pass number of files in source folder to SSIS
            Dts.Variables["User::FilesInSourceDir"].Value = i;
        }
        catch (Exception ex)
        {
            errorText = errorText + ("\r\nError at Name Standardization step: " + ex.Message.ToString()) + $"Filename: {finalFileName}\r\n";
        }

        ///Search for missing files and store paths
        try
        {
            if (i != 4)
            {
                var errors = files.Where(x => !File.Exists(x)).Select(x => x);
                if (errors.Any())
                    errorText = (errorText + $" Missing neccessary files in PR Shared drive. Currently {i} valid files in directory.\r\n\n" + "Files missing\r\n" + string.Join(Environment.NewLine, errors) + "\r\n");
            }
        }
        catch (Exception ex)
        {
            errorText = errorText + ("Error at Finding Missing PR Files step: " + ex.Message.ToString()) + "\r\n\n";
            throw;
        }

        ///Loop through directory to move files to encrypted location
        try
        {
            if (i == 4)
                foreach (FileInfo fi in dirInfo_Source.EnumerateFiles())
                {
                    fi.MoveTo(fileDirectory_Dest + Path.GetFileName(fi.FullName));
                }
        }
        catch (Exception ex)
        {
            errorText = errorText + ("Error at Move Files to Encrypted Directory step: " + ex.Message.ToString()) + "\r\n";
        }
        Dts.TaskResult = (int)ScriptResults.Success;
        Dts.Variables["User::errorText"].Value = errorText;
    }

    #region ScriptResults declaration
    /// <summary>
    /// This enum provides a convenient shorthand within the scope of this class for setting the
    /// result of the script.
    /// 
    /// This code was generated automatically.
    /// </summary>
    enum ScriptResults
    {
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    };
    #endregion

}

}

理想情況下,我希望在需要清理和重命名文件之前移動文件夾中的所有文件,這樣我就不會收到錯誤或將記錄提交到已經存在的數據庫中。

如果您做到了這一步,感謝您抽出寶貴時間,也感謝您花時間閱讀本文。 你是英雄。

據我了解,如果“4 個短名稱”已經存在,您想在執行其他任何操作之前將其移出。 我會在下面,請注意,我沒有運行代碼..我希望我理解你的正確

///Loop through directory to standardize file names
            try
            {
                //Cleanup source folder 
                foreach (string fileShortName in files)
                {
                    if (File.Exists(fileDirectory_Source + fileShortName))
                    {
                        //Time to move the file, its old
                        errorText = errorText + "Old File: " + fileShortName + " moved into the Old File folder.\r\n";

                        File.Move(dirInfo_Source + fileShortName, dirInfo_Source + "Old Files\\" + Path.GetFileNameWithoutExtension(fileShortName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(fileShortName));
                    }
                }

                foreach (FileInfo fi in dirInfo_Source.GetFiles())

暫無
暫無

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

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