Change the location and name of the download for each file
I am doing automation using Selenium with Chrome WebDriver. The application has to do a series of downloads that need to be saved with different names (Data + Report type) and folders that correspond to the type of report I'm downloading.
The problem is that I can only set the default directory when creating a new driver
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("download.default_directory", downloadDirectory);
chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
IWebDriver driver = new ChromeDriver(@"location chromeDriver", chromeOptions);
driver.Navigate().GoToUrl(url);
Therefore, I cannot rename the file name or select the appropriate directory. Does anyone know how I can do this?
+3
source to share
1 answer
You can use MS UI Automation with TestStack.White. It's quite complicated, but it works for sure.
using System.Text.RegularExpressions;
using System.Windows.Automation;
using TestStack.White.InputDevices;
using TestStack.White.UIItems;
using TestStack.White.UIItems.Finders;
using TestStack.White.UIItems.WindowItems;
...
public class SaveAsWindow
{
AutomationElement _dialog;
Window _win;
public SaveAsWindow(string title)
{
List<Window> winList = TestStack.White.Desktop.Instance.Windows();
foreach (Window win in winList)
{
Regex r = new Regex(title, RegexOptions.IgnoreCase);
Match m = r.Match(win.Title);
if (m.Success)
{
_win = win;
}
}
_dialog = _win.GetElement(SearchCriteria.ByControlType(ControlType.Window));
}
public void Close()
{
Condition condition = new PropertyCondition(AutomationElement.NameProperty, "Cancel");
AutomationElement noButton = _dialog.FindFirst(TreeScope.Children, condition);
System.Windows.Point p = noButton.GetClickablePoint();
Mouse.Instance.Click(p);
}
public string FileName
{
set
{
TextBox fileName =_win.Get<TextBox>(SearchCriteria.ByAutomationId("1001"));
fileName.Text = value;
}
}
public void Save()
{
Condition condition = new PropertyCondition(AutomationElement.AutomationIdProperty, "1");
AutomationElement saveButton = _dialog.FindFirst(TreeScope.Children, condition);
System.Windows.Point p = saveButton.GetClickablePoint();
Mouse.Instance.Click(p);
System.Threading.Thread.Sleep(1000);
}
}
//// Usage
IWebDriver driver = new ChromeDriver(@"location chromeDriver", chromeOptions);
driver.Navigate().GoToUrl(url);
// it did something and save as window appears.
var saveWindow = new SaveAsWindow("title of Chrome browser");
saveWindow.FileName = "c:\what-ever.xlsx";
saveWindow.Save();
0
source to share