c# - 如何将流从 HttpContent 结果上传到 Azure 文件存储

标签 c# azure stream azure-storage azure-blob-storage

我正在尝试从数据库中存储的 URL 下载文件列表,然后将它们上传到我的 Azure FileStorage 帐户。我已成功下载文件,并且可以将它们转换为本地存储上的文件,或者将它们转换为文本并上传。但是,当将 pdf 之类的内容转换为文本时,我丢失了数据,并且我不想将文件存储在托管此端点的 Azure 应用程序上,因为我不需要以任何方式操作这些文件。

我尝试从 Stream 上传文件我从 HttpContent 得到使用 UploadFromStream 的对象CloudFile上的方法。每当运行此命令时,我都会收到 InvalidOperationException消息 "Operation is not valid due to the current state of the object."

我尝试转换原始的 StreamMemoryStream同样,但这只是将一个空白文件写入 FileStorage 帐户,即使我将位置设置为 MemoryStream 的开头也是如此。 。我的代码如下,如果有人能指出我缺少哪些信息来完成这项工作,我将不胜感激。

public DownloadFileResponse DownloadFile(FileLink fileLink)
{
    string fileName = string.Format("{0}{1}{2}", fileLink.ExpectedFileName, ".", fileLink.ExpectedFileType);
    HttpStatusCode status;
    string hash = "";
    using (var client = new HttpClient())
    {
        client.Timeout = TimeSpan.FromSeconds(10); // candidate for .config setting
        client.DefaultRequestHeaders.Add("User-Agent", USER_AGENT);

        var request = new HttpRequestMessage(HttpMethod.Get, fileLink.ExpectedURL);
        var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
        var response = sendTask.Result; // not ensuring success here, going to handle error codes without exceptions

        status = response.StatusCode;
        if (status == HttpStatusCode.OK)
        {
            var httpStream = response.Content.ReadAsStreamAsync().Result;

            fileStorage.WriteFile(fileLink.ExpectedFileType, fileName, httpStream);
            hash = HashGenerator.GetMD5HashFromStream(httpStream);
        }
    }

    return new DownloadFileResponse(status, fileName, hash);
}

public void WriteFile(string targetDirectory, string targetFilePath, Stream fileStream)
{
    var options = SetOptions();
    var newFile = GetTargetCloudFile(targetDirectory, targetFilePath);
    newFile.UploadFromStream(fileStream, options: options);
}

public FileRequestOptions SetOptions()
{

    FileRequestOptions options = new FileRequestOptions();

    options.ServerTimeout = TimeSpan.FromSeconds(10);
    options.RetryPolicy = new NoRetry();

    return options;
}

public CloudFile GetTargetCloudFile(string targetDirectory, string targetFilePath)
{
    if (!shareConnector.share.Exists())
    {
        throw new Exception("Cannot access Azure File Storage share");
    }

    CloudFileDirectory rootDirectory = shareConnector.share.GetRootDirectoryReference();
    CloudFileDirectory directory = rootDirectory.GetDirectoryReference(targetDirectory);

    if (!directory.Exists())
    {
        throw new Exception("Target Directory does not exist");
    }

    CloudFile newFile = directory.GetFileReference(targetFilePath);

    return newFile;
}

最佳答案

根据您的描述和代码,我建议您可以先使用Steam.CopyTo将流复制到本地memoryStream,然后将MemoryStream上传到azure文件存储。

更多详细信息,您可以引用以下代码:

我只是更改了 DownloadFile 方法来测试它。

     HttpStatusCode status;

                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(10); // candidate for .config setting
                                                               // client.DefaultRequestHeaders.Add("User-Agent", USER_AGENT);

                    //here I use my blob file to test it              
                    var request = new HttpRequestMessage(HttpMethod.Get, "https://xxxxxxxxxx.blob.core.windows.net/media/secondblobtest-eypt.txt");
                    var sendTask =  client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                    var response = sendTask.Result; // not ensuring success here, going to handle error codes without exceptions
                    status = response.StatusCode;

                    if (status == HttpStatusCode.OK)
                    {
                        MemoryStream ms = new MemoryStream();

                        var httpStream = response.Content.ReadAsStreamAsync().Result;

                        httpStream.CopyTo(ms);
                        ms.Position = 0;
                       WriteFile("aaa", "testaa", ms);
                     //   hash = HashGenerator.GetMD5HashFromStream(httpStream);
                    }
                }

关于c# - 如何将流从 HttpContent 结果上传到 Azure 文件存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078015/

相关文章:

azure - 已验证的开放 API 规范无法上传到 Azure API 管理

stream - 在 Windows Phone 8 SD 卡上读取文件的问题

c# - 如何使用 try/catch/finally C# 有效地管理流

c# - 锁定来自不同线程的方法范围的 "string"对象会阻止执行吗?

azure - 在 Azure DevOps 中安装 Mono 以进行 Nuget 部署

azure - 将域的子文件夹映射到azure应用程序服务

java - 在 Play Framework 中下载动态创建的 zip 文件

C# 正则表达式

c# - WPF c# webbrowser 在顶部菜单上滚动

c# - 关注应用程序 - 与操作系统相关的问题?