Turn your manual testers into automation experts! Request a DemoStart testRigor Free

Selenium with C# Cheat Sheet

Driver Initialization

Chrome IWebDriver driver = new ChromeDriver();
Firefox IWebDriver driver = new FirefoxDriver();
Edge IWebDriver driver = new EdgeDriver();
Safari IWebDriver driver = new SafariDriver();

Locating Elements

By ID: driver.FindElement(By.Id("<element_ID>"));
By Name: driver.FindElement(By.Name("<element_name>"));
By Class Name: driver.FindElement(By.ClassName("<element_class>"));
By Tag Name: driver.FindElement(By.TagName("<html_tag_name>"));
By CSS Selector: driver.FindElement(By.CssSelector("Tag#Value_of_id_attribute"));
By XPath: driver.FindElement(By.XPath("//input[@type='submit']"));
By Link Text: driver.FindElement(By.LinkText("<link_text>"));
By Partial Link Text: driver.FindElement(By.PartialLinkText("<link_text>"));

Working with Files

Upload a file:
using OpenQA.Selenium;

IWebElement fileInput = driver.FindElement(By.Id("file-upload"));
Read data from a text file:
using System.IO;

string[] lines = File.ReadAllLines(@"path\to\your\file.txt");

foreach (string line in lines)
Read data from a CSV file:
using System.IO;
using CsvHelper;

using (var reader = new StreamReader(@"path\to\your\csvfile.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
  var records = csv.GetRecords<dynamic>().ToList();
Read data from an Excel file:
using OfficeOpenXml;
using System.IO;

FileInfo file = new FileInfo(@"path\to\your\excelfile.xlsx");

using (ExcelPackage package = new ExcelPackage(file))
  ExcelWorksheet worksheet = package.Workbook.Worksheets["Sheet1"];
  int rowCount = worksheet.Dimension.Rows;
  int colCount = worksheet.Dimension.Columns;

  for (int row= 1; row <= rowCount; row++) { 
    for (int col = 1; col <= colCount; col++) { 

      Console.Write(worksheet.Cells[row, col].Value.ToString() + "\t"); 


Selenium Navigators

Navigate to a URL driver.Navigate().GoToUrl("<URL>");
Refresh the page driver.Navigate().Refresh();
Navigate forward in browser history driver.Navigate().Forward();
Navigate back in browser history driver.Navigate().Back();

Working with Windows

Get the current window handle:
string mainWindowHandle = driver.CurrentWindowHandle;
Get all window handles:
ReadOnlyCollection<string> allWindowHandles = driver.WindowHandles;
Switch to a specific window:
string windowHandle = driver.CurrentWindowHandle; 
Close the current window:

Working with Frames

Switch to a frame by name or ID:
Switch to a frame by index:
Switch to a frame using a WebElement:
IWebElement iframe = driver.FindElement(By.CssSelector("#modal>iframe")); 
Switch back to the main content:

Working with Dropdowns (Select Elements)

Find the dropdown element:
var dropdown = driver.FindElement(By.Id("dropdown_id"));
Create a Select instance for the dropdown element:
var select = new SelectElement(dropdown);
Select an option by visible text:
select.SelectByText("Option Text");
Select an option by value:
Select an option by index:
Deselect all options (only applicable for multi-select dropdowns):
Get all selected options:
var selectedOptions = select.AllSelectedOptions;
Get the first selected option:
var firstSelectedOption = select.SelectedOption;

Mouse Actions

var actions = new Actions(driver); 
Double click:
Right click:
Drag and drop:
actions.DragAndDrop(sourceElement, targetElement).Perform();
Move to element:

Working with Alerts

Switch to an alert:
IAlert alert = driver.SwitchTo().Alert();
Enter text in an alert:
Dismiss an alert:
Retrieve alert text:
string alertText = alert.Text;

Selenium Operations

Launch a Webpage:
Click a button:
var buttonElement = driver.FindElement(By.CssSelector("<button_element_css_selector>")); 
Print the page title:
var title = driver.Title; 
Wait for an element to be visible:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
var element = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("<element ID>")));
Wait for an element to be clickable:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
var element = wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("<element ID>")));
Implicit wait:
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); // 10 seconds
Explicit wait:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
var element = wait.Until(ExpectedConditions.ElementLocated(By.CssSelector(“<element_css_selector>”))); // 10 seconds
Thread.Sleep(5000); // 5 seconds or 5000 milliseconds
Take a screenshot:
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile("screenshot.png", ScreenshotImageFormat.Png);
Clear the input field text:
var inputElement = driver.FindElement(By.CssSelector("<input_element_css_selector>")); 
Disable a field (set the ‘disabled’ attribute):
((IJavaScriptExecutor)driver).ExecuteScript(“document.querySelector(‘<element_css_selector>’).setAttribute(‘disabled’, ”);”);
Enable a field (remove the ‘disabled’ attribute):

Selenium Grid

Start the hub
java -jar selenium-server-standalone-<version>.jar -role hub
Start a node
java -jar selenium-server-standalone-<version>.jar -role node -hub http://localhost:4444/grid/register


Alternative: write tests without a single line of code

testRigor is an AI-driven, end-to-end testing solution that empowers QA professionals to create and maintain complex automated tests without requiring coding skills. This comprehensive system supports testing of various platforms, including web, mobile, and desktop applications, and is suitable for functional regression, accessibility, load, and performance testing. By leveraging plain English statements and an advanced AI engine, testRigor provides excellent scalability, minimal maintenance, and faster test execution, setting itself apart from coded automation tools such as Selenium.

Organizations that have adopted testRigor have experienced significant improvements in their software testing processes, with increased test coverage, reduced defect escape rates, and accelerated release cycles. The platform not only enhances QA teams and delivery processes but also eliminates the need for maintaining testing infrastructure. The unique approach of testRigor allows for seamless collaboration among team members and ensures tests remain valid even after underlying framework changes or refactoring. This superior choice in test automation provides numerous key benefits, including cost savings, improved communication, and detailed test results for seamless debugging.

Selenium test:

Same test in testRigor:

check if page contains "Welcome Peter"
Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.
Related Articles

Selenium InvalidCoordinatesException: How to Handle?

In Selenium, you will face the InvalidCoordinatesException when the coordinates provided for an action, such as clicking or ...

UnexpectedTagNameException in Selenium: Causes and Remedies

The tag name is a property used in Selenium to retrieve the tag name of a web element. Knowing the tag name helps validate or ...

Why is UnableToSetCookieException Faced in Selenium?

Exceptions are thrown when Selenium WebDriver faces an error during web browser or element interaction. They help in ...