Search your query

Thursday, February 2, 2017

Download the file into Specific local system directory from file management URL

public static void main(Args _args)
{
        DocuRef                     docuReference;
        DocuValue                   docuValue;
        DocuAction                  docuActionClass;
        str                               url;
        Browser                     br = new Browser();
        var                         generator = new Microsoft.Dynamics.AX.Framework.Utilities.UrlHelper.UrlGenerator();

       
       docuReference = DocuRef::find(curExt(), RefRecId) // select the DocuRef table buffer record.

        if(docuReference)
        {
                docuValue = docuReference.docuValue();               
                 url = docuValue.Path;

                if (!url || docuValue.Type == DocuValueType::Others)
                {
                    str accessToken = DocumentManagement::createAccessToken(docuReference);
                    url =           Microsoft.Dynamics.AX.Framework.FileManagement.URLBuilderUtilities::GetDownloadUrl(docuValue.FileId, accessToken);
                } // getting only file management URL without Host.

                var currentHost   = new System.Uri(UrlUtility::getUrl());

                generator.HostUrl = currentHost.GetLeftPart(System.UriPartial::Authority);  
               // this above code is used to find the Host URL; for example, url = "https:usnconeboxax1aos.cloud.onebox.dynamics.com/"; 

                url = generator.HostUrl+"/"+ url;
  
                System.Net.WebClient wc = new System.Net.WebClient();

                wc.DownloadFile(url, @"C:\myfile.xlsx"); // specify the file path in second parameter.


If you want to convert this file into IO Stream (Memory stream): Use below code.

               System.IO.Stream        stream = File::UseFileFromURL(url);

Convert this stream into file again:

              var fileStream = new System.IO.FileStream(@"C:\myfile1.xlsx.", System.IO.FileMode::Create, System.IO.FileAccess::Write);
                stream.CopyTo(fileStream);

          }
}

2 comments:

  1. Hi Hussain,

    I am using your code to download the attached file, but it is not working for me. can you help me

    By nirmal

    ReplyDelete
    Replies
    1. Hi Nimral..
      did you find any solution?
      please share as this above code is not working for me also.

      Delete