问题
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