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

Cod*_*nga 4 c# webdav winscp nextcloud

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

得到教训:

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

然而,WinSCP、nextcloud 文档中没有可用的示例,这里也找不到任何内容。

Cod*_*nga 5

// 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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