Download file to local folder Vault 2015 C# API

Download file to local folder Vault 2015 C# API

Anonymous
Not applicable
2,544 Views
3 Replies
Message 1 of 4

Download file to local folder Vault 2015 C# API

Anonymous
Not applicable

I tried the following to download the selected files to the desired locaiton

 

 

if(Global.variables.filesColl.Count > 0)
            {
                foreach (var file in Global.variables.filesColl)
                {
                    File selectedFile = null;
                    // Look of the File object. 
                    if (file.TypeId == SelectionTypeId.File)
                    {
                        // our ISelection.Id is really a File.MasterId
                        selectedFile = Global.variables.connection.WebServiceManager.DocumentService.GetLatestFileByMasterId(file.Id);
                    }
                    else if (file.TypeId == SelectionTypeId.FileVersion)
                    {
                        // our ISelection.Id is really a File.Id
                        selectedFile = Global.variables.connection.WebServiceManager.DocumentService.GetFileById(file.Id);

                    }
                    if (selectedFile != null)
                    {
                        
                        using (WebServiceManager serviceManager = Global.variables.connection.WebServiceManager)
                        {
                            Autodesk.Connectivity.WebServices.File localFile = serviceManager.DocumentService.GetFileById(selectedFile.Id);
                            var FileDownloadTicket = serviceManager.DocumentService.GetDownloadTicketsByFileIds(new long[] { selectedFile.Id });
                            FilestoreService fileStoreService = serviceManager.FilestoreService;
                            var fileBytes = fileStoreService.DownloadFilePart(FileDownloadTicket[0].Bytes, 0, localFile.FileSize, false);
                            System.IO.File.WriteAllBytes(path, fileBytes);
                        }
                        
                    }
                        
                }
            }

 

I get the following error no matter which path I give.

 

 

---------------------------
Vault Professional 2015
---------------------------
System.UnauthorizedAccessException: Access to the path 'C:\A2KApps\FileStore' is denied.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes, Boolean checkHost)

   at SendFile.Helper.vaultHelper.downloadVaultFile() in h:\Copy\Projects\AutoDesk\Vault\DotNET\Vault15_SendFile\HelloWorld\Helper\vaultHelper.cs:line 49

   at SendFile.App.SendFileWin.btn_send_Click(Object sender, RoutedEventArgs e) in h:\Copy\Projects\AutoDesk\Vault\DotNET\Vault15_SendFile\HelloWorld\App\SendFileWin.xaml.cs:line 33

   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)

   at System.Windows.Controls.Primitives.ButtonBase.OnClick()

   at System.Windows.Controls.Button.OnClick()

   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)

   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)

   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)

   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)

   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)

   at System.Windows.Input.InputManager.ProcessStagingArea()

   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)

   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)

   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)

   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)

   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)

   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)

   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)

   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)

   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)

   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)

   at Connectivity.Explorer.Framework.ApplicationClass.Run(String[] args)

   at Connectivity.Application.Product.MainEntry.Main(String[] args)
---------------------------
OK   
---------------------------

 

 

0 Likes
2,545 Views
3 Replies
Replies (3)
Message 2 of 4

Anonymous
Not applicable

Good afternoon, Raghulan.

 

Do you have any solution by this post?

0 Likes
Message 3 of 4

psaarloos
Collaborator
Collaborator

Hi Pashin,

 

I would advise to use the new AcquireFiles method provided by the FileManager. This method makes sure references are updates during the download process in case any file was renamed or moved in Vault.

 

            File file = _connection.WebServiceManager.DocumentService.GetFileById(fileId);
            FileIteration fileIteration = new FileIteration(_connection, file);
            FilePathAbsolute filePath = _connection.WorkingFoldersManager.GetPathOfFileInWorkingFolder(fileIteration);

            try
            {
                AcquireFilesSettings settings = new AcquireFilesSettings(_connection);
                settings.AddFileToAcquire(fileIteration, AcquireFilesSettings.AcquisitionOption.Download);
                settings.OptionsRelationshipGathering.FileRelationshipSettings.IncludeChildren = true;
                settings.OptionsRelationshipGathering.FileRelationshipSettings.RecurseChildren = true;
                settings.OptionsRelationshipGathering.FileRelationshipSettings.IncludeLibraryContents = true;
                settings.OptionsRelationshipGathering.FileRelationshipSettings.VersionGatheringOption = Autodesk.DataManagement.Client.Framework.Vault.Currency.VersionGatheringOption.Latest;
                settings.OptionsRelationshipGathering.FileRelationshipSettings.ReleaseBiased = false;
                settings.OptionsResolution.OverwriteOption = AcquireFilesSettings.AcquireFileResolutionOptions.OverwriteOptions.ForceOverwriteAll;
                AcquireFilesResults results = _connection.FileManager.AcquireFiles(settings);
            }
            catch (Exception ex)
            {

            }

 

Regards,
Pim Saarloos
Product Manager
If my post answers your question, please click the "Accept as Solution" button. Kudos are much appreciated!
Message 4 of 4

Anonymous
Not applicable

Good afternoon, Pim.

 

Thank you, Pim for your solution, but for this case, I would also like to share a solution. And this solution is also not bad.

 

 

    Public Sub GetActualProjectSchedule()
        ' fs.FileSystemItems - список информации обо всех файлах в хранилище Vault
        ' Здесь я получаю все файлы, у которых в названии имеется шифр проекта и имя файла «План-график проекта»
        Dim curProjectSchedule = From a In fs.FileSystemItems
                                 Where a.ItemPath.Contains(bsiProjectNumberVal.Caption)
                                 Where a.ItemPath.Contains("Schedule")
                                 Select a

        ' Я мог, в принципе повторно не искать файл в списке, но на всякий случай это сделал!!! Уже с расширением файла
        Dim xlsProjectFile = From a In curProjectSchedule
                             Where a.ItemPath.Contains("Shedule.xlsx")

        ' Соединение с Vault
        Dim results As VDF.Vault.Results.LogInResult = VDF.Vault.Library.ConnectionManager.LogIn(ServerName, VaultName, "", "", VDF.Vault.Currency.Connections.AuthenticationFlags.WindowsAuthentication, Nothing)
        ' Если соединение не произошло - выходим из процедуры
        If results.Success = False Then
            Return
        End If
        ' Если соединение произошло - устанавливаем соединение в параметр
        Dim connection As VDF.Vault.Currency.Connections.Connection = results.Connection
        ' Получение всех файлов по MasterId
        Dim vaultFiles As File() = connection.WebServiceManager.DocumentService.GetLatestFilesByMasterIds(New Long() {xlsProjectFile(0).ItemMasterId})
        ' Получение для текущего файла массивы байт
        Dim FileDownloadTicket = connection.WebServiceManager.DocumentService.GetDownloadTicketsByFileIds(New Long() {vaultFiles(0).Id})
        ' Выгружаем массив байт в поток
        Dim fileBytes As IO.Stream = connection.WebServiceManager.FilestoreService.DownloadFilePart(FileDownloadTicket(0).Bytes, 0, vaultFiles(0).FileSize, True)
        ' Выгружаем из потока байты
        Dim fileData As Byte()
        Using streamReader = New IO.MemoryStream()
            fileBytes.CopyTo(streamReader) ' Копируем массив в поток
            fileData = streamReader.ToArray() ' Превращаем поток в массив байт, который можно преобразовать в файл
        End Using
        ' Создаём файл на основе массива байт из потока
        System.IO.File.WriteAllBytes(Environ("TEMP") & "\test.xlsx", fileData)
do_again:
        ' Ждём пока файл загрузится в папку! Как?
        ' Для этого постоянно пытаемся его скопировать в ту же папку под другим именем
        Try
            IO.File.Copy(Environ("TEMP") & "\test.xlsx", Environ("TEMP") & "\shedule.xlsx", True)
        Catch ex As Exception
            Threading.Thread.Sleep(300)
            GoTo do_again
        End Try
        ' После завершения выгрузки путь к нужному файлу фиксируем в переменной
        XLSX = Environ("TEMP") & "\shedule.xlsx"
        ' Завершаем соединение, чтобы ничего не подвисло!
        VDF.Vault.Library.ConnectionManager.LogOut(connection)
    End Sub

 

I hope that this option will also be useful for someone.

 

0 Likes