【问题标题】:How to access nextcloud files in C# by using WebDav?如何使用 WebDav 在 C# 中访问 nextcloud 文件?
【发布时间】:2019-10-30 05:02:05
【问题描述】:

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

经验教训:

  1. 提供的服务器名称没有协议,这是由 SessionOptions.Protocol
  2. 根文件夹不能为空,必须至少为“/”
  3. 下一个云提供商/配置定义了根url,所以remote.php后面的“webdav”或“dav”是预定义的。一般在设置部分使用nextcloud的webapp时可以在左下角看到
  4. “文件/用户”或“文件/用户名”不一定是必需的 - 也由主机/配置定义
  5. 连接用户必须具有给定目录的访问权限,您应该通过在 TransferOptions 中提供 FilePermissions 向其他人提供文件访问权限(如果需要)

但是,在 WinSCP、nextcloud 文档中没有工作示例,在这里也找不到任何东西。

【问题讨论】:

  • 请将帖子编辑为一个问题和一个单独的答案,例如“如何访问...”,再加点肉。然后发布解决方案作为答案。然后它将适合网站的格式。也请查看help center 并采取tour
  • 编辑完成 - 不改变上下文 ....

标签: c# webdav winscp nextcloud


【解决方案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);
        }
    }
}

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

【讨论】: