Azure文件存储-上传后文件已损坏 [英] Azure File Storage - File is corrupted once uploaded

查看:135
本文介绍了Azure文件存储-上传后文件已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于在azure文件存储容器中上传文件的这段代码.

I have this code which I'm using for uploading files in azure file storage container.

        var originalFileName = GetDeserializedFileName(result.FileData.First());

        var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);

        var uploadFolder = "/AzureDocuments" + '/' + correctLoanId ;
        var patString = HttpContext.Current.Server.MapPath(uploadFolder) + "/" + originalFileName;

        if(!Directory.Exists(HttpContext.Current.Server.MapPath(uploadFolder)))
        {
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadFolder + '/' + correctLoanId));
        }

        if (!File.Exists(patString))
        {
            File.Copy(uploadedFileInfo.FullName, patString);
        }

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("StorageConnectionString"));

        CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

        CloudFileShare share = fileClient.GetShareReference("documents");
        CloudFileDirectory rootDir = share.GetRootDirectoryReference();

        CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(correctLoanId);

        sampleDir.CreateIfNotExists();

        CloudFile cloudFile = sampleDir.GetFileReference(originalFileName);

        try
        {
            //Open a stream from a local file.
            Stream fileStream = File.OpenRead(patString);
            cloudFile.UploadFromStreamAsync(fileStream);
            fileStream.Dispose();

        }
        catch (Exception ex)
        {
        }

文件已正确上传,并且以天蓝色显示了正确的大小,但是当我下载文件时,我收到错误消息,指出文件已损坏.

The file is correctly uploaded and the correct size is shown in azure but when I'm downloading the file I'm getting error message that the file is corrupted.

知道我做错什么了吗?

Any idea if I'm doing something wrong?

推荐答案

文件损坏的原因是由于以下代码行:

The reason your file is corrupted is because of the following line of code:

cloudFile.UploadFromStreamAsync(fileStream);

基本上,您正在启动一个异步过程,但不等待它完成.要解决此问题,您可以执行以下任一操作:

Essentially you're starting an async process but not waiting for it to complete. To fix, you could do either of the following:

使用此方法的sync版本:

cloudFile.UploadFromStream(fileStream);

或者,等待async方法完成(推荐):

Or, wait for async method to finish (recommended):

await cloudFile.UploadFromStreamAsync(fileStream);

请注意,如果您使用的是异步方法,则还需要使调用方法也异步.

Please note that if you're using async method, you would need to make the calling method async as well.

这篇关于Azure文件存储-上传后文件已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆