1

I am using Renci.SshNet to connect to SFTP and loop through files which is present in a folder one by one, and delete once we read a file. Then we continue with next file. But I am observing a issue where I am not able to delete file. When I try sftp.DeleteFile(item.FullName); it gives "no such file" error message.

Below is the sample code which is giving the issue mentioned.

using (SftpClient sftp = new SftpClient(con))
{
    sftp.Connect();

    var fileList = sftp.ListDirectory("/Foldername");
    foreach (var item in fileList)
    {
        StringBuilder sb = new StringBuilder();
        using (StringWriter sw = new StringWriter(sb))
        using (XmlTextWriter writer = new XmlTextWriter(sw))
        //reading files from MFT
        using (XmlReader reader = XmlTextReader.Create(sftp.OpenRead(item.FullName)))
        {
            while (reader.Read())
            {
                if (reader.LocalName == "Employee" && reader.IsStartElement())
                {
                    writer.WriteStartElement(
                        reader.Prefix, reader.LocalName, reader.NamespaceURI);
                    writer.WriteAttributes(reader, true);
                }
            }
        }
        sb = null;
        // This line fails and I get "no such file" error message.
        sftp.DeleteFile(item.FullName); 
    }

    sftp.Disconnect();
}

But if I disconnect the connection after reading file and again connect I am able to delete file.

This workaround fixes the issue:

sftp.Disconnect(); // If I disconnect and connect again, I am able to delete the file
sftp.Connect(); // Connecting again
sftp.DeleteFile(item.FullName); // Now delete file works
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
techresearch
  • 119
  • 3
  • 14

1 Answers1

1

You do not close the remote file stream, so the file is locked and cannot be deleted.

Try this:

using (var remoteFileStream = sftp.OpenRead(item.FullName))
using (XmlReader reader = XmlTextReader.Create(remoteFileStream))
{
    // ...
}

The XmlTextReader does not seem to dispose the underlying Stream. See Why is FileStream not closed by XmlReader.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992