예제 #1
0
        public string DownloadFileToOpen(CloudFile toOpen, Action <long, long> callback)
        {
            try
            {
                var fileName = Path.GetFileName(toOpen?.Uri?.LocalPath?.Replace("/", "\\") ?? "");
                var tmpPath  = Path.GetTempPath();

                string fullTmpPath = Path.Combine(tmpPath, fileName)?.Replace("\\", "/");

                if (File.Exists(fullTmpPath))
                {
                    File.Delete(fullTmpPath);
                }

                using (var fs = new ObservableFileStream(fullTmpPath, FileMode.OpenOrCreate, callback))
                {
                    toOpen?.DownloadToStream(fs);
                }

                return(fullTmpPath);
            } catch (Exception ex)
            {
                return("");
            }
        }
        public Stream DownloadFileContentAsStream(string fileShareName, string fileName = "")
        {
            CloudFileClient fileClient = new CloudFileClient(fileURI, creds);
            // Create a CloudFileClient object for credentialed access to Azure Files.
            Stream s = null;

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference(fileShareName);

            // Ensure that the share exists.
            if (share.Exists())
            {
                try
                {
                    // Get a reference to the root directory for the share.
                    CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                    CloudFile          cloudFile = rootDir.GetFileReference(fileName);
                    cloudFile.DownloadToStream(s);
                    return(s);
                }
                catch (Exception e)
                {
                    throw new StorageAccountException("Error while attempting to get contents", e);
                }
            }
            else
            {
                DirectoryNotFoundException e = new DirectoryNotFoundException(string.Format("The file share '{0}' does not exist.", fileShareName));
                throw new StorageAccountException("Error while attempting to get content", e);
            }
        }
예제 #3
0
        public MemoryStream GetCloudFileStream(string fileDirectory, string fileName)
        {
            MemoryStream memstream = new MemoryStream();

            try
            {
                fileDirectory = CleanRelativeCloudDirectoryName(fileDirectory);

                CloudStorageAccount cloudStorageAccount = GetCloudStorageAccount();
                CloudFileClient     fileClient          = GetCloudFileClient(cloudStorageAccount);
                CloudFileShare      share    = GetCloudFileShareReference(fileClient);
                CloudFileDirectory  shareDir = GetCloudFileDirectory(share, fileDirectory);
                if ((shareDir != null) && shareDir.Exists())
                {
                    CloudFile file = GetCloudFile(shareDir, fileName);
                    if (file != null)
                    {
                        file.DownloadToStream(memstream);
                    }
                }
            }
            catch (Exception oExeption)
            {
                oExeption.Log($"GetCloudFileStream- {fileName}");
            }
            return(memstream);
        }
예제 #4
0
 private MemoryStream GetStream(CloudFile cloadFile)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         cloadFile.DownloadToStream(ms);
         return(ms);
     }
 }
예제 #5
0
    public static void Download(CloudFile blocktype, string path)
    {
        Directory.CreateDirectory(Utils.getPath());

        using (var fileStream = System.IO.File.OpenWrite(Utils.getPath() + blocktype.Name))
        {
            blocktype.DownloadToStream(fileStream);
        }
    }
예제 #6
0
        private static T DownloadTheAudio <T>(Func <byte[], T> eitherRight, CloudFile fileToDownload)
        {
            byte[] fileBytes = null;
            using (MemoryStream ms = new MemoryStream())
            {
                fileToDownload.DownloadToStream(ms);
                fileBytes = ms.GetBuffer();
            }

            return(eitherRight(fileBytes));
        }
예제 #7
0
        public static void DownloadFile(string path)
        {
            var value = path;

            if (value != null && value != "")
            {
                string[] fname      = value.Split('/');
                string   foldername = "";
                int      count      = 0;
                for (int i = fname.Length - 2; i <= (fname.Length - 2); i--)
                {
                    if (i != 0)
                    {
                        count++;
                        foldername += fname[count] + '/';
                    }
                    else
                    {
                        break;
                    }
                }
                //get share name
                string ShareName = fname[0].ToLower();
                CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
                CloudFileClient     cloudFileClient     = cloudStorageAccount.CreateCloudFileClient();
                CloudFileShare      cloudFileShare      = cloudFileClient.GetShareReference(ShareName);
                CloudFileDirectory  root           = cloudFileShare.GetRootDirectoryReference();
                CloudFileDirectory  directoryToUse = root.GetDirectoryReference(foldername);
                CloudFile           cloudFile      = directoryToUse.GetFileReference(fname.Last());
                //checking for file exist on directory or not
                if (directoryToUse.Exists())
                {
                    //if yes store it to local path of your project with given file name
                    var memStream = new MemoryStream();
                    using (var fileStream = System.IO.File.OpenWrite(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Download.pdf")))
                    {
                        cloudFile.DownloadToStream(memStream);
                    }
                    Console.WriteLine("File saved in {0}", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Download.pdf"));
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("File not exist on Azure.");
                }
            }
        }
예제 #8
0
 public byte[] GetFile(string nombreArchivo)
 {
     try
     {
         // Buscamos el nombre de nuestro archivo en nuestro directorio
         CloudFile cloudFile = this.directorio.GetFileReference(nombreArchivo);
         // Descargamos el contenido del archivo como file
         using (var content = new MemoryStream())
         {
             cloudFile.DownloadToStream(content);
             return(content.ToArray());
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
예제 #9
0
        /// <summary>
        /// GetCloudFileStream - ORIG
        /// </summary>
        /// <param name="imageFileDirectory"></param>
        /// <param name="imageFileName"></param>
        /// <returns></returns>
        protected MemoryStream GetCloudFileStreamOrig(string imageFileDirectory, string imageFileName)
        {
            MemoryStream memstream = new MemoryStream();

            try
            {
                CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(azureFileShareConnectionString);

                CloudFileClient fileClient = cloudStorageAccount.CreateCloudFileClient();
                CloudFileShare  share      = fileClient.GetShareReference(azureFileShareName);
                if (!share.Exists())
                {
                    throw new ShareNotFoundException(azureFileShareName);
                }
                // Get a reference to the root directory for the share
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the image directory
                CloudFileDirectory shareDir = rootDir.GetDirectoryReference(imageFileDirectory);

                if (!shareDir.Exists())
                {
                    throw new FolderNotFoundException(imageFileDirectory);
                }
                // get a cloud file reference to the image
                CloudFile file = shareDir.GetFileReference(imageFileName);
                if (!file.Exists())
                {
                    throw new FileNotFoundException(imageFileDirectory, imageFileName);
                }

                file.DownloadToStream(memstream);
            }
            catch (Exception oExeption)
            {
                oExeption.Log($"GetCloudFileStreamOrig - {imageFileDirectory}\\{imageFileName}]");
            }
            return(memstream);
        }
예제 #10
0
        public Stream GetFile(string fileName)
        {
            Stream result = new MemoryStream();

            // Ensure that the directory exists.
            if (fileDirectory.Exists())
            {
                // Get a reference to the file we created previously.
                CloudFile file = fileDirectory.GetFileReference(fileName);

                // Ensure that the file exists.
                if (file.Exists())
                {
                    // Get the contents of the file.
                    file.DownloadToStream(result);

                    //Necesario porque cuando vuelva a leerse el stream, lo retorna vacío
                    result.Position = 0;
                }
            }

            return(result);
        }
 /// <summary>
 /// Downloads a file from the Microsoft Azure File service by calling <see cref="CloudFile.DownloadToStream(Stream, AccessCondition, FileRequestOptions, OperationContext)"/>.
 /// </summary>
 /// <param name="cancellationToken">The token used to signal cancellation request.</param>
 public override void Run(CancellationToken cancellationToken)
 {
     _cloudFile.DownloadToStream(Stream.Null);
 }
예제 #12
0
        public JsonResult GetUserDocuments(string userId, int taxYear, int?skip, int?amount)
        {
            bool downloadSuccessful = true;
            var  results            = new List <Tuple <string, string, string> >();

            using (var db = new WorktripEntities())
            {
                try
                {
                    Regex filePattern = new Regex(@"http.*\/.*\/(?<directory>.*)\/(?<filename>.*)");

                    var user = db.Users.FirstOrDefault(u => u.Id == userId);

                    var miscDocs  = db.UserMiscDocs.Where(d => d.UserId == userId && d.Year == taxYear);
                    var taxReturn = db.UserTaxReturns.Where(d => d.UserId == userId && d.Year == taxYear);

                    miscDocs  = miscDocs.OrderBy(d => d.Id);
                    taxReturn = taxReturn.OrderBy(d => d.Id);

                    if (skip.HasValue)
                    {
                        miscDocs  = miscDocs.Skip(skip.Value);
                        taxReturn = taxReturn.Skip(skip.Value);
                    }

                    if (amount.HasValue)
                    {
                        miscDocs  = miscDocs.Take(amount.Value);
                        taxReturn = taxReturn.Take(amount.Value);
                    }

                    var fileUrls = miscDocs.Select(d => d.Path).ToList();
                    fileUrls.AddRange(taxReturn.Select(d => d.Path).ToList());

                    var parsedFilePaths = new List <Tuple <string, string> >();

                    foreach (var url in fileUrls)
                    {
                        Match match = filePattern.Match(url);

                        if (match.Success)
                        {
                            var newTuple = new Tuple <string, string>(
                                match.Groups["directory"].Value,
                                match.Groups["filename"].Value
                                );

                            parsedFilePaths.Add(newTuple);
                        }
                    }

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

                    CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

                    CloudFileShare share = fileClient.GetShareReference("worktripdocs");

                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                    CloudFileDirectory userDir = null;

                    var userDirName = "";

                    foreach (var parsedPath in parsedFilePaths)
                    {
                        if (userDirName != parsedPath.Item1)
                        {
                            userDir = rootDir.GetDirectoryReference(parsedPath.Item1);

                            if (!userDir.Exists())
                            {
                                continue;
                            }

                            userDirName = parsedPath.Item1;
                        }

                        var filename = parsedPath.Item2;

                        CloudFile file = userDir.GetFileReference(filename);

                        if (!file.Exists())
                        {
                            continue;
                        }

                        file.FetchAttributes();

                        string fileContents = "";

                        if (file.Properties.ContentType != null &&
                            file.Properties.ContentType.StartsWith("image/"))
                        {
                            MemoryStream fileStream = new MemoryStream();

                            file.DownloadToStream(fileStream);

                            fileContents = ConvertImageStreamToBase64String(fileStream);
                        }
                        else if (file.Properties.ContentType.ToLower() == "application/pdf")
                        {
                            MemoryStream fileStream = new MemoryStream();
                            file.DownloadToStream(fileStream);

                            fileContents = ConvertStreamToBase64String(fileStream);
                        }
                        else
                        {
                            fileContents = file.DownloadText();
                        }

                        results.Add(
                            new Tuple <string, string, string>(filename, file.Properties.ContentType, fileContents)
                            );
                    }
                }
                catch (Exception e)
                {
                    //Do some error logging here..
                    downloadSuccessful = false;
                }
            }

            if (downloadSuccessful)
            {
                return(Json(new {
                    status = 0,
                    files = results
                }));
            }
            else
            {
                return(Json(new { status = -1, message = "Error in downloading files" }));
            }
        }
예제 #13
0
        public JsonResult GetSingleUserTaxReturn(string userId, int taxYear)
        {
            bool downloadSuccessful = true;
            var  results            = new List <Tuple <string, string, byte[]> >();

            using (var db = new WorktripEntities())
            {
                try
                {
                    Regex filePattern = new Regex(@"http.*\/.*\/(?<directory>.*)\/(?<filename>.*)");

                    var user      = db.Users.FirstOrDefault(u => u.Id == userId);
                    var taxReturn = db.UserTaxReturns.Where(d => d.UserId == userId && d.Year == taxYear);

                    taxReturn = taxReturn.OrderBy(d => d.Id);

                    var fileUrls = new List <UserTaxReturn>();
                    if (taxReturn.Count() != 0)
                    {
                        fileUrls.Add(taxReturn.AsEnumerable().Last());
                        byte[] bytes = new byte[64000];

                        var parsedFilePaths = new List <Tuple <string, string> >();

                        foreach (var url in fileUrls)
                        {
                            Match match = filePattern.Match(url.Path);

                            if (match.Success)
                            {
                                var newTuple = new Tuple <string, string>(
                                    match.Groups["directory"].Value,
                                    match.Groups["filename"].Value
                                    );

                                parsedFilePaths.Add(newTuple);
                            }
                        }

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

                        CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

                        CloudFileShare share = fileClient.GetShareReference("worktripdocs");

                        CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                        CloudFileDirectory userDir = null;

                        var userDirName = "";

                        foreach (var parsedPath in parsedFilePaths)
                        {
                            if (userDirName != parsedPath.Item1)
                            {
                                userDir = rootDir.GetDirectoryReference(parsedPath.Item1);

                                if (!userDir.Exists())
                                {
                                    continue;
                                }

                                userDirName = parsedPath.Item1;
                            }

                            var filename = parsedPath.Item2;

                            CloudFile file = userDir.GetFileReference(filename);

                            if (!file.Exists())
                            {
                                continue;
                            }

                            file.FetchAttributes();

                            string fileContents = "";

                            if (file.Properties.ContentType.ToLower() == "application/pdf")
                            {
                                MemoryStream fileStream = new MemoryStream();
                                file.DownloadToStream(fileStream);
                                bytes        = fileStream.ToArray();
                                fileContents = ConvertStreamToBase64String(fileStream);
                            }
                            else
                            {
                                fileContents = file.DownloadText();
                            }

                            results.Add(
                                new Tuple <string, string, byte[]>(filename, file.Properties.ContentType, bytes)
                                );
                        }
                    }
                }
                catch (Exception e)
                {
                    //Do some error logging here..
                    downloadSuccessful = false;
                }
            }

            if (downloadSuccessful && results.Count > 0)
            {
                return(Json(new MyJsonResult
                {
                    status = 0,
                    fileName = results.ElementAtOrDefault(0).Item1,
                    fileContentType = results.ElementAtOrDefault(0).Item2,
                    fileContents = results.ElementAtOrDefault(0).Item3
                }));
            }
            else
            {
                return(Json(new { status = -1, message = "Error in downloading files" }));
            }
        }