我似乎想不通这件事。当我手动下载这些文件(使用与WebClient相同的网址)时,它们似乎工作得很好。
作为背景,我正在尝试下载我们的Azure服务器上工作项的附件,并将它们上传到TFS2015 DevOps。我已经尝试过将文件下载到我的本地(这就是我在下载时知道它们被损坏的原因),也尝试过直接将文件作为流文件并使用WorkItemTrackingHttpClient.CreateAttachmentAsync()函数上传到Azure DevOps。
有人知道我做错了什么吗?
我将WebClient与硬编码凭据和我自己的(默认)凭据一起使用。两者都表现出相同的行为。
public async Task<WorkItem> AddAttachmentFromSourceURL(int workItemID, string url, string fileName)
{
AttachmentReference attachment;
using (var webClient = WorkItemClientHelpers.CreateWebClient())
{
//this is only commented out so I could download the files (i.e. these are the two different methods I've tried).
//await using var attStream = webClient.OpenRead(url);
//attachment = WorkItemTrackingHttpClient.CreateAttachmentAsync(uploadStream: attStream, fileName: fileName).Result; // upload the file
var filePath = $"C:\\TempAttachment\\{fileName}";
webClient.DownloadFile(url, filePath);
await using FileStream attStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
attachment = WorkItemTrackingHttpClient.CreateAttachmentAsync(uploadStream: attStream, fileName: fileName).Result; // upload the file
}
JsonPatchDocument jsonPatchDoc = new JsonPatchDocument();
jsonPatchDoc.Add(new JsonPatchOperation()
{
Operation = Operation.Add,
Path = "/relations/-",
Value = new
{
rel = "AttachedFile",
url = attachment.Url,
attributes = new { comment = "Comments for the file " + fileName }
}
});
WorkItem updatedWorkItem = await WorkItemTrackingHttpClient.UpdateWorkItemAsync(jsonPatchDoc, workItemID);
return updatedWorkItem;
}
发布于 2021-09-15 23:24:38
我在这篇文章中找到了答案:WebClient download file corrupted (我发誓,我之前做了详尽的搜索!)
基本上,该文件需要解压缩。添加这个类成功了(这是链接问题中的答案):
public class myWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
https://stackoverflow.com/questions/69200664
复制相似问题