2016-12-03 48 views
0

我無法找到使用WinSCP .NET程序集的良好WebDAV實現示例。WinSCP .NET WebDAV示例

具體而言,我正在尋找一些將文件推送到WebDAV服務器的代碼。

有人請提供一些示例C#代碼來幫助我開始?

回答

0

這裏是我最後一個WinSCP .NET WebDAV文件推送實現的示例。

不漂亮,但它似乎做的工作。

希望這可以爲別人節省幾個小時。

快速注意:WebDavUploadSettings.Default.XXXX是我如何訪問我的設置文件,其中存儲了所有的連接信息。

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(); 
    } 
}