![](/img/trans.png)
[英]How can I move my files from my directory to another directory without getting an exception
[英]How can I fix my code to move files that already exist to another directory?
这是我的第一个 C# 脚本,也是第一个基于非 SQL 的脚本。我真的为此感到自豪(如果没有这个社区的帮助,我不可能这么快完成,谢谢!),但我知道它会各种乱七八糟。
该脚本遍历单个目录中的所有文件,从文件名中删除特殊字符,并将文件重命名为标准的、用户友好的名称。 该脚本正在目录中寻找一组特定的文件。 如果它发现一个不应该在目录中的文件,它会将文件移动到一个安全文件夹并重命名它。 如果文件夹
我正在处理 4 个具有动态名称的文件,这些文件将包括数字和特殊字符。 重命名过程分两步进行:
从名称中删除特殊字符和数字。 例如:从“EOY 12.21.2018 - 12.28.2018 PRF.xls”到“EOYPRF.xls”
重命名文件以清楚地标记文件是什么。 例如:从“EOYPRF.xls”到“EOY_CompanyName.xls”
可能有文件意外添加到此目录中,由于它们是工资单文件,因此它们是高度机密的,除非需要移动,否则不能移动(仅当它们是 4 个文件之一时),因此我将它们移动到文件存储在同一目录中的子目录并重命名它们。
我还试图说明我的脚本或流程是否在中途搞砸了。 此脚本是在 SSIS 中运行的更大自动化过程的一部分,因此存在许多故障点。 脚本可能会失败并在目录中留下 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.