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;
            return fileExists;

Thanks for reading How to Verify file download in C#

« Prev Post

No comments:

Post a Comment

Fixing javascript error: Cannot read properties of null (reading 'querySelector') issue when using CSS identifier in selenium

 JavaScript is another way to interact with web elements when normal selenium methods fail to act. But one issue with javascript is, it does...