Cod*_*nga 4 c# webdav winscp nextcloud
当尝试通过 WinSCP 访问 nextcloud 的 WebDav API 时,我面临着正确使用根文件夹、远程路径等的几个问题。为了节省其他人的时间,这里是我想出的将文件上传到的工作代码远程(共享)文件夹。
得到教训:
然而,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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以为其他人节省一些时间。