Azure File Storage - File is corrupted once uploaded

瘦欲@ 提交于 2019-12-13 07:36:43

问题


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?


回答1:


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:

Use sync version of this method:

cloudFile.UploadFromStream(fileStream);

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.



来源:https://stackoverflow.com/questions/39721926/azure-file-storage-file-is-corrupted-once-uploaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!