web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Project Service Automation forum

Uploading file to Azure File storage

(0) ShareShare
ReportReport
Posted on by 65

Hi, All,

I am trying to create a comma separated text file and then upload that in the azure file storage. Below is my code. The file is getting created in the azure storage, but the file contains nothing. Can any one help me on this.

below is the code.

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.File;

public class AzureStoreageUploadCheck
{        
    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {  
        TextStreamIo                  file = TextStreamIo::constructForWrite();
        str                     totalFile;
        container               mainContainer;
        
        totalFile = "A,B,,    ,Cust001";        

        mainContainer = conNull();
        mainContainer = conIns(mainContainer,1,totalFile);
        
        file.writeExp(mainContainer);
        File::SendFileToUser(file.getStream(), "Demo.txt");

        System.IO.MemoryStream memoryStream;

        var storageCredentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials('DEMO2018', 'XXXXX');

        CloudStorageAccount storageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount(storageCredentials, true);

        CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

        CloudFileShare share = fileClient.GetShareReference('bankpaymentfile');

        if (share.Exists(null, null))
        {
            CloudFileDirectory rootDir = share.GetRootDirectoryReference();

            CloudFileDirectory fileDir = rootDir.GetDirectoryReference('UnProcessed');

            if (fileDir.Exists(null, null))
            {
                CloudFile cfile = fileDir.GetFileReference('file.csv');

                if (cfile.Exists(null, null))
                {
                    memoryStream = new System.IO.MemoryStream();
                    cfile.DownloadToStream(memoryStream, null, null, null);
                }
                else
                {
                    str a = File::SendFileToTempStore(file.getStream(),"file.txt");
                    cfile.UploadFromStreamAsync(file.getStream()).Wait();
                    info("Upload");
                }
            }
        }

        
    }

}
I have the same question (0)
  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    Do you delete the file every time? If not, UnProcessed/file.csv is already there from an older run and your upload code won't be called at all (which can also be verified in debugger).

  • Prateep Ghosh Profile Picture
    65 on at

    Hi Martin,

    I was deleting the file manually from the azure portal. The same file when I am using File:SendFileToUser is coming with correct value. But after uploading to the portal, when I am downloading, I am not able to see any value. It is just a blank file with 0 kB.

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    Maybe a silly question, but which storage are you looking at? Your code seems to write both to file storage and blob storage.

    Also, try writing the file synchronously (UploadFromStream()), it will make easier for you to catch exceptions. When using asynchronous processing, you may need to check whether it succeeded.

  • Suggested answer
    Community Member Profile Picture
    on at

    Hi! I had the same problem

    Try adding this code right before you upload you file.

    var fileContent = file.getStream();

    if (fileContent .CanSeek)

    {
    fileContent .Seek(0, System.IO.SeekOrigin::Begin);
    }

    ........

    then use fileContent in your code like this

    cfile.UploadFromStreamAsync(fileContent).Wait();
  • Verified answer
    Prateep Ghosh Profile Picture
    65 on at

    Hi,

    Thanks for replying. Yesterday I was able to fix the problem. Below is the code which I am using.

    @Knut  I will try your code and will update here.

    using Microsoft.Azure;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using Microsoft.WindowsAzure.Storage.File;
    //using System.IO;
    
    public class AzureStoreageUploadCheck
    {        
        /// <summary>
        /// Runs the class with the specified arguments.
        /// </summary>
        /// <param name = "_args">The specified arguments.</param>
        public static void main(Args _args)
        {  
            TextStreamIo                  file = TextStreamIo::constructForWrite();
            str                     totalFile;
            container               mainContainer;
            CustTable               custTable;
            
            totalFile = "A,B,,    ,Cust001";        
    
            mainContainer = conNull();
            mainContainer = conIns(mainContainer,1,totalFile);
            
            file.writeExp(mainContainer);
    
            str filetemppath = File::SendFileToTempStore(file.getStream(),"Test.txt");
            System.IO.Stream fileStream = File::UseFileFromURL(filetemppath);
    
            var storageCredentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials('XXXX', 'PASS');
            CloudStorageAccount storageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount(storageCredentials, true);
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare share = fileClient.GetShareReference('bankpaymentfile');
            if (share.Exists(null, null))
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                CloudFileDirectory fileDir = rootDir.GetDirectoryReference('UnProcessed');
                if (fileDir.Exists(null, null))
                {
                    CloudFile cfile = fileDir.GetFileReference('Test.txt');
                    if (cfile.Exists(null, null))
                    {
                        //memoryStream = new System.IO.MemoryStream();
                        //cfile.DownloadToStream(memoryStream, null, null, null);
                    }
                    else
                    {
                        str a = File::SendFileToTempStore(file.getStream(),"file.txt");
                        try
                        {
                            cfile.UploadFromStream(fileStream,null,null,null);
                            info("Upload");
                        }
                        catch(Exception::Error)
                        {
                            info("a");
                        }
                    }
                }
            }
                    
        }
    
    }


  • Prateep Ghosh Profile Picture
    65 on at

    Hi Knut,

    I tried the below code, but still it was uploading a blank file. No data was there.

    using Microsoft.Azure;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using Microsoft.WindowsAzure.Storage.File;
    using PwCAzureConnector;
    //using System.IO;
    
    public class AzureStoreageUploadCheck
    {        
        /// <summary>
        /// Runs the class with the specified arguments.
        /// </summary>
        /// <param name = "_args">The specified arguments.</param>
        public static void main(Args _args)
        {  
            TextStreamIo                  file = TextStreamIo::constructForWrite();
            str                     totalFile;
            container               mainContainer;
            CustTable               custTable;
            Microsoft.WindowsAzure.Storage.AccessCondition acccond;
            Microsoft.WindowsAzure.Storage.File.FileRequestOptions options;
            Microsoft.WindowsAzure.Storage.OperationContext context;
            totalFile = "A,B,,    ,Cust001";        
    
            mainContainer = conNull();
            mainContainer = conIns(mainContainer,1,totalFile);
            
            file.writeExp(mainContainer);
    
            str filetemppath = File::SendFileToTempStore(file.getStream(),"Test.txt");
            System.IO.Stream fileStream = File::UseFileFromURL(filetemppath);
            
            var fileContent = file.getStream();
            if (fileContent.CanSeek)
            {
                fileContent.Seek(0, System.IO.SeekOrigin::Begin);
            }
    
            
            var storageCredentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials('XXX', 'pass');
            CloudStorageAccount storageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount(storageCredentials, true);
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare share = fileClient.GetShareReference('bankpaymentfile');
            if (share.Exists(null, null))
            {
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();
                CloudFileDirectory fileDir = rootDir.GetDirectoryReference('UnProcessed');
                if (fileDir.Exists(null, null))
                {
                    CloudFile cfile = fileDir.GetFileReference('Test.txt');
                    if (cfile.Exists(null, null))
                    {
                        //memoryStream = new System.IO.MemoryStream();
                        //cfile.DownloadToStream(memoryStream, null, null, null);
                    }
                    else
                    {
                        str a = File::SendFileToTempStore(file.getStream(),"file.txt");
                        try
                        {
                            //cfile.UploadFromStream(file.getStream(),null,null,null);
                            //cfile.UploadFromStream(fileContent,null,null,null);
                            cfile.UploadFromStreamAsync(fileContent).Wait();
                            info("Upload");
                        }
                        catch(Exception::Error)
                        {
                            info("a");
                        }
                    }
                }
            }
                    
        }
    
    }


  • Community Member Profile Picture
    on at

    Hi! I'm not sure were you code fails, but I below is my method for uploading a file. Hope this will help you out.

    public static boolean uploadFileToAzureFileStorage(System.IO.Stream _fileContentInStream , str _folderName, str _fileName)
    {
    SomeParameterTable someParameterTable = SomeParameterTable::find();

    try
    {
    Microsoft.WindowsAzure.Storage.Auth.StorageCredentials storageCredentials = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(someParameterTable.AzureStorageAccount,someParameterTable.AzureStorageCredentialKey);
    Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount(storageCredentials, true);
    Microsoft.WindowsAzure.Storage.File.CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
    Microsoft.WindowsAzure.Storage.File.CloudFileShare share = fileClient.GetShareReference(someParameterTable.AzureStorageFileShare);

    if (! share.Exists(null, null))
    {
    throw error(strFmt("Azure file share is missing!", someParameterTable.AzureStorageFileShare, someParameterTable.AzureStorageAccount));
    }

    Microsoft.WindowsAzure.Storage.File.CloudFileDirectory cloudDir = share.GetRootDirectoryReference();

    container conFolders = str2con(_folderName, '/');

    for (int i = 1; i <= conlen(conFolders); i++)
    {
    str folderName = conpeek(conFolders, i);
    cloudDir = cloudDir.GetDirectoryReference(folderName);
    cloudDir.CreateIfNotExists(null, null);
    }

    Microsoft.WindowsAzure.Storage.File.CloudFile file = cloudDir.GetFileReference(_fileName);

    //have to run Seek on Stream. The file will be empty if not
    if (_fileContentInStream.CanSeek)
    {
    _fileContentInStream.Seek(0, System.IO.SeekOrigin::Begin);
    }

    file.UploadFromStream(_fileContentInStream,null,null,null);

    return true;
    }
    catch
    {
    return false;
    }
    }

  • Manoj Veeramanoharan Profile Picture
    on at

    Knut ,

    How do you populate data into the file , lets say i need 10 columns and 10 rows . you use _fileContentInStream to pass it as paramter . But how did you populate data into _fileContentInStream . 

    Please let me know. Thanks and Appreciated

  • Community Member Profile Picture
    on at

    Hi, here is a real simple exaple of how to create a file. When the file is created use the getStream-method to populate data into _fileContentInStream

    class KSF_createFile //simple example for creating file

    {        

       public static void main(Args _args)

       {

           int codepageParameter = 1252;

           TextStreamIo file = TextStreamIo::constructForWrite(codepageParameter);

           str lineContent;

           //create line 1

           lineContent = '1;';

           lineContent += '2;';

           file.write(lineContent);

           lineContent = '';

           //create line 2

           lineContent = '11;';

           lineContent += '12;';

           file.write(lineContent);

           lineContent = '';

           var fileCreatedOK = KSF_Helper::uploadFileToAzureFileStorage(file.getStream(),'outfolder','testfile.csv');

           Info(strFmt('filesstatus %1',fileCreatedOK));

       }

    }

  • Manoj Veeramanoharan Profile Picture
    on at

    Knut

    Thanks Much . Do u have anything for copy file .Or to move file from one location to another  . Below is not working .

    /// <summary>
    /// Move the file from current directory to destination/error/archive directory
    /// </summary>
    /// <param name = "_currentDir"><c>CloudFileDirectory</c> for current file</param>
    /// <param name = "_currentFile"><c>CloudFile</c> of current file</param>
    /// <param name = "_currentFileName">Current file name in string</param>
    /// <param name = "_addDateStamp">Add date stamp to existig file name to create new file in destination directory</param>
    /// <param name = "_errored">Move to Error destination directory in case of error or move to Archive destination directory</param>
    /// <param name = "_deleteCurrentFile">Delete current file after moving in case of true</param>
    /// <param name = "_destDir"><c>CloudFileDirectory</c> for destination directory which overrides "_errored" parameter</param>
    public void moveFile(CloudFileDirectory _currentDir,CloudFile _currentFile,str _currentFileName,boolean _addDateStamp,boolean _errored,boolean _deleteCurrentFile = false,CloudFileDirectory _destDir = null)
    {

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard > Project Service Automation

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans