简体   繁体   中英

Delete files after upload with WinSCP .NET assembly

My script is very simple

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = conHostName,
    UserName = conUserName,
    Password = conPasswort,
    SshHostKeyFingerprint = conSshHostKeyFingerprint
};

using (Session session = new Session())
{
    session.Open(sessionOptions);

    TransferOptions transferOptions = new TransferOptions();
    transferOptions.TransferMode = TransferMode.Binary;

    TransferOperationResult transferResult;

    if(modus == "download")
    {
        transferResult = session.GetFiles(
            remoteDirectoryDownload, localDirectoryDownload, false, transferOptions);
    } 
    else
    {
        transferResult = session.PutFiles(
            localDirectoryUpload, remoteDirectoryUpload, false, transferOptions);
    }

    transferResult.Check();

    foreach (TransferEventArgs transfer in transferResult.Transfers)
    {
        try
        {
            Console.WriteLine("Delete File: {0}", transfer.FileName);
            session.RemoveFiles(transfer.FileName);
        }
        catch (Exception e)
        {

            Console.WriteLine("Error: {0}", e);
        }
    }
}

When I do the download, then the files from the remote host would be transferred and deleted on the remote host. But when I make the upload from the local folder, then the uploads would work but the file on the local folder would not be deleted. I get no error.

I start this with my user. I am the owner of this files and I can delete them self manually.

Also when I set a breakpoint on session.RemoveFiles , then the correct file with the correct local path would be shown.

Maybe you have a idea for me where my fail is.

Session.RemoveFiles deletes remote files only. It cannot delete local files. For deleting local files, use the standard .NET File.Delete .

Though easier (and better) is to pass true to the remove (3rd) argument of Session.GetFiles / Session.PutFiles .

It's better than your current code even for downloads, as it deletes all successfully downloaded files. While your current code won't delete any files, if only part of the files are downloaded successfully.

Also, you are using the default TransferOptions , so that code is redundant.

In the end, you can simplify your code to:

using (Session session = new Session())
{
    session.Open(sessionOptions);

    if (modus == "download")
    {
        session.GetFiles(remoteDirectoryDownload, localDirectoryDownload, true).Check();
    } 
    else
    {
        session.PutFiles(localDirectoryUpload, remoteDirectoryUpload, true).Check();
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM