简体   繁体   中英

How to download and open XML file via SFTP?

I need to open XML file (create XmlDocument) without creating local copy. Using SSH.NET, I came up with this code:

var connectionInfo = new ConnectionInfo("host",
    "username",
    new PasswordAuthenticationMethod("username", "password"));

using (var client = new SftpClient(connectionInfo))
{
    client.Connect();

    System.IO.MemoryStream mem = new System.IO.MemoryStream();

    client.DownloadFile("filename.xml", mem);

    mem.Position=0;

    using(XmlReader reader = XmlReader.Create(mem))
    {
        var docc = new XmlDocument();
        docc.Load(mem);
    }

    client.Disconnect();
}

But is gets stuck on docc.Load(mem) . What could be the problem?

mem object looks like this:

在此处输入图片说明

Note that here:

using(XmlReader reader = XmlReader.Create(mem))
{
    var docc = new XmlDocument();
    docc.Load(mem);
}

You are not using variable reader at all. Either change to

using(XmlReader reader = XmlReader.Create(mem))
{
    var docc = new XmlDocument();
    docc.Load(reader);
}

or remove reader at all:

docc.Load(mem);

While the answer by @Evk solves your immediate problem, your code is still inefficient.

Use SftpClient.OpenRead to directly stream the file to XmlReader :

using (XmlReader reader = XmlReader.Create(client.OpenRead("filename.xml"))
{
    // process the XML
}

or to XmlDocument :

var docc = new XmlDocument();
docc.Load(client.OpenRead("filename.xml"));

This way, you do not waste a memory by creating another copy of the file in MemoryStream .

It looks like you wrote xml file to stream and now, stream is pointed at the end of xml file. Try setting stream.position to 0 before loading.

stream.Position = 0;

Try this:

using (var client = new SftpClient(connectionInfo))
{
    client.Connect();

    System.IO.MemoryStream mem = new System.IO.MemoryStream();

    client.DownloadFile("filename.xml", mem);
    // Set stream position
    mem.Position = 0;
    using(XmlReader reader = XmlReader.Create(mem))
    {
        var docc = new XmlDocument();
        docc.Load(mem);
    }

    client.Disconnect();
}

I would also change the code to dispose the memory stream correctly...

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