在 UWP 项目中将文件上传到 WebDAV

Upload file to WebDAV in UWP project

我正在尝试使用 Portable-WebDAV-Library 在 WebDAV 存储上实现写入操作,但我的代码

var credentials = new NetworkCredential("user", "password");
var webDavSession = new WebDavSession(@"https://...", credentials);
Uri uri = new Uri("https://.../SubDir/somefile.txt");

try
{
  using (MemoryStream ms = new MemoryStream())
  {
    using (StreamWriter sw = new StreamWriter(ms))
    {
      sw.Write(DateTime.Now.ToString("G"));
      sw.Flush();
      ms.Position = 0;
    }

    await webDavSession.UploadFileAsync(uri, ms);
  }
}
catch (Exception ex)
{
}

抛出异常 "Cannot use the specified Stream as a Windows Runtime IInputStream because this Stream is not readable." 我已经对 IRandomAccessStream 和 IOutputStream 进行了试验,但产生了其他异常。

问题是,StreamWriter 在其 using 块的末尾关闭了 MemoryStream。所以将 }await webDavSession.UploadFileAsync(uri, ms); 的前面移到后面解决了问题:

之前:

  ms.Position = 0;
}

await webDavSession.UploadFileAsync(uri, ms);

之后:

  ms.Position = 0;
  await webDavSession.UploadFileAsync(uri, ms);
}