November 24, 2019

How to Verify file download in C#

  November 24, 2019
Sometimes there comes scenario which we need to ensure a file is downloaded to PC when we click on the download button.
For this we can use the basic C# based code to check a particular file is downloaded in the given location in last two minutes.

This may not be a accurate validation, still we can use this to avoid manual validation if this is done very frequently in the given scenario.

We can use below code for the same purpose.


        /// <summary>
        ///  Method to verify whether the downloaded file exists based on filename and text format.
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool VerifyDownloadedFile(string folderPath, string fileName, string fileType)
        {
            bool fileExists = false;
            string[] filePaths = Directory.GetFiles(folderPath);
            foreach (string filedownloaded in filePaths)
            {
                //Read file name.
                string result = Path.GetFileName(filedownloaded);
                //Truncate filename after space.
                var splitvalue = result.LastIndexOf(' ');
                if (splitvalue >= 0)
                    result = result.Substring(0, splitvalue);
                result = result + fileType;
                if (result.Contains(fileName))
                {
                    FileInfo thisFile = new FileInfo(filedownloaded);
                    //Ensures that file is downloaded within two minutes.
                    if (thisFile.LastWriteTime.ToShortTimeString() == DateTime.Now.ToShortTimeString() ||
                    thisFile.LastWriteTime.AddMinutes(2).ToShortTimeString() == DateTime.Now.ToShortTimeString())
                    {
                        fileExists = true;
                        break;
                    }
                }
            }
            return fileExists;
        }
logoblog

Thanks for reading How to Verify file download in C#

Previous
« Prev Post

No comments:

Post a Comment

How to send email from current Outlook instance using Java + VBScript

If we are using .Net, we can easily access outlook and send emails using its own libraries. But what if we are using Java? Here we can seek ...