November 24, 2019

How to Verify file download in C# + Selenium

  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# + Selenium

Previous
« Prev Post

No comments:

Post a Comment

Bookmark this website for more workarounds and issue fixes.

Verify Zip file contents without extracting using C# + Selenium

While doing automation testing, we may get a scenario where we need to download a zip file and to validate the contents inside it. One way t...