简体   繁体   中英

WinSCP .NET WebDAV Example

I am unable to find a good WebDAV implementation example utilizing WinSCP .NET assembly.

Specifically I am looking for some code that will push a file to a WebDAV server.

Could someone please provide some sample C# code to help get me started?

Here is my example of a WinSCP .NET WebDAV file push implementation that I ended up with.

Is not pretty but it seems to do the job.

Hopefully this saves someone else a frustrating couple hours.

Quick note: WebDavUploadSettings.Default.XXXX is how I am accessing my settings file where all my connection info is stored.

public static void SendFileWebDav(string FileToSend)
{
    if (!DoesFileExist(FileToSend))
    {
        throw new Exception(string.Format("Cannot Find File {0}", FileToSend));
    }
    SessionOptions sessionOptions = new SessionOptions();
    sessionOptions.UserName = WebDavUploadSettings.Default.Username;
    sessionOptions.Password = WebDavUploadSettings.Default.Password;
    if (string.IsNullOrWhiteSpace(WebDavUploadSettings.Default.FolderPathToPushTo)) //WINSCP will throw an error if root directory doesn't start with /
    {
        //Haven't tested this.
        sessionOptions.WebdavRoot = "/";
    }
    else
    {
        sessionOptions.WebdavRoot = WebDavUploadSettings.Default.FolderPathToPushTo.ToString(); //Added .ToString() here because I was getting 404 error other wise? Maybe because is was not reading in the setting correctly.
    }
    //Make sure you define this as a URL without protocal. (Leave off Https:// and Http://)
    sessionOptions.HostName = WebDavUploadSettings.Default.Website;
    sessionOptions.Protocol = Protocol.Webdav;
    Session WebDavSession = new Session();

    try
    {
        WebDavSession.Open(sessionOptions);
        TransferOptions TransferOptions = new TransferOptions();
        TransferOptions.TransferMode = TransferMode.Automatic;
        TransferOperationResult transferResult;
        transferResult = WebDavSession.PutFiles(FileToSend,Path.GetFileName(FileToSend), false, TransferOptions);
        transferResult.Check();
    }
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        WebDavSession.Close();
    }
}

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