首页 > 解决方案 > 如何使用 WebDav 在 C# 中访问 nextcloud 文件?

问题描述

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

得到教训:

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

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

标签: c#webdavwinscpnextcloud

解决方案


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

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


推荐阅读