如何使用WebDav访问C#中的nextcloud文件?

时间:2019-06-16 08:01:43

标签: c# webdav winscp nextcloud

当尝试通过WinSCP访问nextcloud的WebDav API时,我面临正确使用根文件夹,远程路径等问题。 为了节省其他时间,这是我想到的将文件上传到远程(共享)文件夹中的工作代码。

经验教训:

  1. 提供的服务器名称不带协议,由服务器定义 SessionOptions.Protocol
  2. 根文件夹不能为空,必须至少为“ /”
  3. 下一个云提供程序/配置定义了根URL,因此在remote.php之后预定义了“ webdav”或“ dav”。通常,在设置部分使用nextcloud的网络应用时,您可以在左下角看到它
  4. “文件/用户”或“文件/用户名”不是必需的-由托管者/配置也定义
  5. 连接用户必须具有对给定目录的访问权限,您应该通过在TransferOptions中提供FilePermissions为其他人(如果需要)提供文件访问权限

但是,WinSCP(nextcloud文档)中没有可用的示例,在这里也找不到任何内容。

1 个答案:

答案 0 :(得分:1)

// Setup session options
var sessionOptions = new SessionOptions
{
    Protocol = Protocol.Webdav,
    HostName = server,
    WebdavRoot = "/remote.php/webdav/" 
    UserName = user,
    Password = pass,
};

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

    var files = Directory.GetFiles(sourceFolder);

    logger.DebugFormat("Got {0} files for uploading to nextcloud from folder <{1}>", files.Length, sourceFolder);

    TransferOptions tOptions = new TransferOptions();
    tOptions.TransferMode = TransferMode.Binary;
    tOptions.FilePermissions = new FilePermissions() { OtherRead = true, GroupRead = true, UserRead = true };

    string fileName = string.Empty;
    TransferOperationResult result = null;

    foreach (var localFile in files)
    {
        try
        {
            fileName = Path.GetFileName(localFile);

            result = session.PutFiles(localFile, string.Format("{0}/{1}", remotePath, fileName), false, tOptions);

            if (result.IsSuccess)
            {
                result.Check();

                logger.DebugFormat("Uploaded file <{0}> to {1}", Path.GetFileName(localFile), result.Transfers[0].Destination);
            }
            else
            {
                logger.DebugFormat("Error uploadin file <{0}>: {1}", fileName, result.Failures?.FirstOrDefault().Message);
            }
        }
        catch (Exception ex)
        {
            logger.DebugFormat("Error uploading file <{0}>: {1}", Path.GetFileName(localFile), ex.Message);
        }
    }
}

希望这可以为其他人节省一些时间。