c# - 如何使用 WebDav 在 C# 中访问 nextcloud 文件?
问题描述
当尝试通过 WinSCP 访问 nextcloud 的 WebDav API 时,我在正确使用根文件夹、远程路径等方面遇到了几个问题。为了节省其他人一些时间,这是我想出的将文件上传到的工作代码远程(共享)文件夹。
得到教训:
- 服务器名称不提供协议,这由 SessionOptions.Protocol 定义
- 根文件夹不能为空,必须至少为“/”
- 下一个云提供商/配置定义了根 url,因此 remote.php 之后的“webdav”或“dav”是预定义的。一般在设置部分使用nextcloud的webapp时可以在左下角看到
- “文件/用户”或“文件/用户名”不一定是必需的 - 也由主机/配置定义
- 连接用户必须对给定目录具有访问权限,您应该通过在 TransferOptions 中提供 FilePermissions 向其他人提供文件访问权限(如果需要)
但是,在 WinSCP、nextcloud 文档中没有工作示例,在这里也找不到任何东西。
解决方案
// 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);
}
}
}
希望这可以为其他人节省一些时间。
推荐阅读
- javascript - 在 node.js --prof 输出中,这个名字奇怪的 C++ 函数在做什么?
- javascript - 音频文件的混合内容
- c++ - MobileNet SSD V2 转换的 tflite 模型的错误输出
- php - php脚本找不到包含文件
- python - 在python中添加365天至今
- winapi - 如何在 win32 中使用 SetTextColor 更改文本 SetDlgItemText 的颜色?
- math - 我将使用“光线投射器”选择“对象”之一进行放大
- python - MNIST图像数据上的EM算法python
- java - 如何在不发送实体的完整 json 的情况下更新对象
- azure - Azure 事件网格出口限制