Wait for finished download file in selenium and c#

戏子无情 提交于 2019-12-24 06:27:16

问题


I have some problem. I download a file after click icon on web application. My next step is carried out faster than the record file. I watn to use some watit, but i have any idea how ?

Somebody know how write that wait ?


回答1:


I use the following script (filename should be passed in).

The first part waits till the file appears on disk (fine for chrome)

The second part waits till it stops changing (and starts to have some content)

var downloadsPath = Environment.GetEnvironmentVariable("USERPROFILE") + @"\Downloads\" + fileName;
for (var i = 0; i < 30; i++)
{
    if (File.Exists(downloadsPath)) { break; }
    Thread.Sleep(1000);
}
var length = new FileInfo(downloadsPath).Length;
for (var i = 0; i < 30; i++)
{
    Thread.Sleep(1000);
    var newLength = new FileInfo(downloadsPath).Length;
    if (newLength == length && length != 0) { break; }
    length = newLength;
}



回答2:


I started from Dmitry`s answer and added some support for controlling the timeouts and the polling intervals. This is the solution:

/// <exception cref="TaskCanceledException" />
internal async Task WaitForFileToFinishChangingContentAsync(string filePath, int pollingIntervalMs, CancellationToken cancellationToken)
{
    await WaitForFileToExistAsync(filePath, pollingIntervalMs, cancellationToken);

    var fileSize = new FileInfo(filePath).Length;

    while (true)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            throw new TaskCanceledException();
        }

        await Task.Delay(pollingIntervalMs, cancellationToken);

        var newFileSize = new FileInfo(filePath).Length;

        if (newFileSize == fileSize)
        {
            break;
        }

        fileSize = newFileSize;
    }
}

/// <exception cref="TaskCanceledException" />
internal async Task WaitForFileToExistAsync(string filePath, int pollingIntervalMs, CancellationToken cancellationToken)
{
    while (true)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            throw new TaskCanceledException();
        }

        if (File.Exists(filePath))
        {
            break;
        }

        await Task.Delay(pollingIntervalMs, cancellationToken);
    }
}

And you use it like this:

using var cancellationTokenSource = new CancellationTokenSource(timeoutMs);
WaitForFileToFinishChangingContentAsync(filePath, pollingIntervalMs, cancellationToken);

A cancellation operation will be automatically triggered after the specified timeout.




回答3:


Maybe look into these: How can I ask the Selenium-WebDriver to wait for few seconds in Java?

https://msdn.microsoft.com/en-us/library/system.threading.thread.sleep%28v=vs.110%29.aspx



来源:https://stackoverflow.com/questions/28586602/wait-for-finished-download-file-in-selenium-and-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!