I have this code in C# (script task SSIS)
public void Main()
{
// TODO: Add your code here
string Server = Dts.Variables["FTPServer"].Value.ToString();
string User = Dts.Variables["FTPUser"].Value.ToString();
string Password = Dts.Variables["FTPPassword"].Value.ToString();
int port = (int) Dts.Variables["FTPPort"].Value;
string remoteFolder = Dts.Variables["FTPRemoteFolder"].Value.ToString();
string archiveFolder = remoteFolder + "/TEST_ARCHIVES/" ;
moveFiles(Server, port, Password, User, remoteFolder, archiveFolder);
Dts.TaskResult = (int)ScriptResults.Success;
}
void moveFiles(string FTPServer,int port,string FTPPassword,string FTPUser,string oldPath,string newPath)
{
try
{
using (var client = new SftpClient(FTPServer, port, FTPUser, FTPPassword))
{
client.Connect();
if (!client.IsConnected)
{
throw new Exception("Not Connected");
}
List <SftpFile> files = (List<SftpFile>)client.ListDirectory(oldPath);
foreach (var file in files)
{
if(file.Name.StartsWith("EXP_"))
{
file.MoveTo(newPath + file.Name );
}
}
client.Disconnect();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
The above script is from a script task SSIS and it can move files having name starts with "EXP_" from oldPath (folder 1 in sftp server) to the newPath (folder 2 in sftp server). It works fine correctly when the file does not exists in folder 2. But when I try to move a file that exists already in the newPath (folder 2 in sftp server) it fails when running the SSIS package. What I need to implement:
NB: I'm using in references: using Renci.SshNet.Sftp;
so the function File.Exists()
not appear, it's a specific situation with functions that uses Renci.SshNet.Sftp
MoveTo has an override that allows you to specify if it should overwrite the destination file, if it exists. Simply add a "true" to your file.MoveTo() call as a second parameter like this and give it a try:
foreach (var file in files)
{
if(file.Name.StartsWith("EXP_"))
{
file.MoveTo(newPath + file.Name, true);
}
}
See the Microsoft Documentation for this method for more information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.