How can I remove google chrome cookies - c#

I'm trying to remove cookies of chrome browser. Firstly I declared the path
string chromeLocation1 = "C:\\Users\\" + Environment.UserName.ToString() + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Local Storage";
When I try to run my remove code "The file is in use by another program or user" error appears. So I tried to kill chrome.exe's proccess
foreach (var process in Process.GetProcessesByName("chrome.exe"))
{
process.Kill();
}
But now it gives me "Access Denied" error even I run it as administrator. What should I do to remove these cookies?

You can delete all cookies with selenium framework.
1) Install selenium framework - Selenium WebDriver and Selenium WebDriver Support Classes (the easiest way to do this is by using NuGet)
2) Use the following code to delete all cookies:
var chromeUserData = "C:\\Users\\" + Environment.UserName.ToString(CultureInfo.InvariantCulture) + "\\AppData\\Local\\Google\\Chrome\\User Data";
var chromeAdvancedSettings = "chrome://settings/clearBrowserData";
var options = new ChromeOptions();
options.AddArgument("--lang=en");
options.AddArgument("--user-data-dir=" + chromeUserData);
options.LeaveBrowserRunning = false;
var driver = new ChromeDriver(options);
driver.Navigate().GoToUrl(chromeAdvancedSettings);
var frame = driver.FindElement(By.XPath("//iframe[#src='chrome://settings-frame/clearBrowserData']"));
var frameDriver = driver.SwitchTo().Frame(frame);
var dropDown = new SelectElement(frameDriver.FindElement(By.Id("clear-browser-data-time-period")));
dropDown.SelectByIndex(4);
var elm = driver.FindElement(By.Id("delete-cookies-checkbox"));
if (!elm.Selected) elm.Click();
elm = driver.FindElement(By.XPath("//button[#id='clear-browser-data-commit']"));
elm.Click();
var waiter = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
waiter.Until(wd => wd.Url.StartsWith("chrome://settings"));
driver.Navigate().GoToUrl("chrome://newtab");
[Selenium documentation]

if You want to delete your browser all data using C# language then you can delete each browser history,cookies etc (all data) using different code.
Here i write some code for deleting all data of Internet explorer
1-- Delete all data/History of Internet Explorer in a button click (Window Form application or WPF application)
private void button1_Click(object sender, EventArgs e)
{
//For internet explorer
System.Diagnostics.Process.Start("rundll32.exe", "InetCpl.cpl,ClearMyTracksByProcess 255");
}
2--- Now the importent browser Google Chrome (the mystery because everyone try to delete all history of it using SQLite but it wrong). Dont use SQLite database because google chrome Hold all data( History, Cookies, and etc) in following location
C:\Users\UserName(Your PC Name)\AppData\Local\Google\Chrome\User Data
just delete all 'User Data' Folder or all the folders and files within it. then you will see your all history and cookies clear.
Following is the code for it.
private void button1_Click(object sender, EventArgs e)
{
//For internet explorer
System.Diagnostics.Process.Start("rundll32.exe", "InetCpl.cpl,ClearMyTracksByProcess 255");
// for Google Chrome.
string rootDrive = Path.GetPathRoot(Environment.SystemDirectory); // for getting primary drive
string userName = Environment.UserName; // for getting user name
// first close all the extension of chrome (close all the chrome browser which are opened)
try
{
Process[] Path1 = Process.GetProcessesByName("chrome");
foreach (Process p in Path1)
{
try
{
p.Kill();
}
catch { }
p.WaitForExit();
p.Dispose();
}
System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(rootDrive + "Users\\"+userName+"\\AppData\\Local\\Google\\Chrome\\User Data");
try
{
foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
file.Delete();
}
}
catch { }
try
{
foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
{
dir.Delete(true);
}
}
catch { }
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
label1.Text = " History Deleted successfully.";
}

you can clear the cookies history and cache by following the below console application
https://stackoverflow.com/a/57111667/9377382

Related

How to keep Chrome open when opened using Selenium WebDriver in Mac

I am trying to open Chrome and load a webpage using Selenium C# WebDriver. The issue I am having is, Chrome opens and loads the page and closes right away.
Here is my code:
//I copied the chromedriver.exe to my project directory
using (var driver = new ChromeDriver(Environment.CurrentDirectory))
{
try
{
//Maximize the browser
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("http://www.google.com");
}
catch (TimeoutException te) {
string y = te.Message;
}
catch (Exception ce) {
string k = ce.Message;
}
}
Any idea how to resolve it would be helpful.

How can I open a .pdf file in the browser from a Xamarin UWP project?

I have a Xamarin Project where I generate a .pdf file from scratch and save it in my local storage. This works perfectly fine and can find it and open it in the disk where I saved it. However, I need to open the .pdf file immediately after creation programmatically.
I already tried different variations using Process and ProcessStartInfo but these just throw errors like "System.ComponentModel.Win32Exception: 'The system cannot find the file specified'" and "'System.PlatformNotSupportedException'".
This is basically the path I am trying to open using Process.
var p = Process.Start(#"cmd.exe", "/c start " + #"P:\\Receiving inspection\\Inspection Reports\\" + timestamp + ".pdf");
I also tried ProcessStartInfo using some variations but I'm getting the same errors all over and over.
var p = new Process();
p.StartInfo = new ProcessStartInfo(#"'P:\\Receiving inspection\\Inspection Reports\\'" + timestamp + ".pdf");
p.Start();
The better way is that use LaunchFileAsync method to open file with browser. You could create FileLauncher DependencyService to invoke uwp LaunchFileAsync method from xamarin share project.
Interface
public interface IFileLauncher
{
Task<bool> LaunchFileAsync(string uri);
}
Implementation
[assembly: Dependency(typeof(UWPFileLauncher))]
namespace App14.UWP
{
public class UWPFileLauncher : IFileLauncher
{
public async Task<bool> LaunchFileAsync(string uri)
{
var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(uri);
bool success = false;
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not
}
return success;
}
}
}
Usage
private async void Button_Clicked(object sender, EventArgs e)
{
await DependencyService.Get<IFileLauncher>().LaunchFileAsync("D:\\Key.pdf");
}
Please note if you want to access D or C disk in uwp, you need add broadFileSystemAccess capability. for more please refer this .
Update
If the UWP files are network based, not local zone based, you could use Xamarin.Essentials to open file with browser. And you must specify the privateNetworkClientServer capability in the manifest. For more please refer this link.

Open link in browser from code behind of installed application C#

I have made a winform application. When I run the app in visual studio, following code works to open a link from DataGridView link column.
System.Diagnostics.Process.Start("chrome.exe",
grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
But when I install the build and try to do the same thing, nothing happens. Is there any other setting that I need to make.
Please help.
If you want to open link link from your DataGridView, you should actually pass url not web browser, ie.:
System.Diagnostics.Process.Start(grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
It will end up trying to open given url with default browser for OS.
Ofc make sure that link of url from url is properly formatted.
If chrome.exe doesn't work for launching, maybe try shortened one: chrome?
Can you also confirm that Win+R (a.k.a. Run...) and then chrome.exe actually opens up Chrome?
If not, can you check if
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ contains chrome.exe entry?
If so, maybe url formatting is wrong?
You can open a URL in browser with the following snippets:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = "http://google.com";
process.Start();
or
System.Diagnostics.Process.Start("http://google.com");
In your example, to allow users to launch it from the DataGridView, you should simply define a click event like this:
private void grdRelLinks_CellContentClick(object pSender, DataGridViewCellEventArgs pArgs)
{
if (pArgs.RowIndex > -1 && pArgs.ColumnIndex == 2)
{
string url = grdRelLinks.Rows[pArgs.RowIndex].Cells[pArgs.ColumnIndex].Value.ToString();
if(!string.IsNullOrWhiteSpace(url))
System.Diagnostics.Process.Start(url);
}
}
This worked for me.
private void OnGridViewContentClick(object sender, EventArgs e)
{
string chromeExePath = CheckIfChromeIsInstalled();
if (!string.IsNullOrEmpty(chromeExePath))
{
MessageBox.Show("Yayy Chrome.exe was found !");
//Path is not null:
Process.Start(chromeExePath, "http://www.google.de");//Here you can also enter the URL you get from your GridView
string url = grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString();
if(!url.StartsWith("http")
{
url = $"http://{url}";
}
Process.Start(chromeExePath, url);
}
else
{
MessageBox.Show("Chrome.exe not found");
}
}
private string CheckIfChromeIsInstalled()
{
DirectoryInfo programFiles = new DirectoryInfo(Environment.GetEnvironmentVariable("PROGRAMFILES"));//Find your Programs folder
DirectoryInfo[] dirs = programFiles.GetDirectories();
List<FileInfo> files = new List<FileInfo>();
Parallel.ForEach(dirs, (dir) =>
{
files.AddRange(dir.GetFiles("chrome.exe", SearchOption.AllDirectories)); //Search for Chrome.exe
});
//files should only contain 1 entry
//Return path of chrom.exe or null
return (files.Count > 0) ? files[0].FullName : null;
}
NOTE: Starting this in an extra Thread could be useful !
EDIT :
Can you please check if cmd.exe works with start chrome.exe "your URL" ?!

How to open HTML file with default browser and delete it after user viewed it?

I try to open temporary HTML file with default browser and delete the file then:
var tempFileName = Path.ChangeExtension(Path.GetTempFileName(), "html");
// I save document to temp file here...
Process process = null;
try
{
process = Process.Start(tempFileName);
}
catch (Win32Exception)
{
}
catch (ObjectDisposedException)
{
}
catch (FileNotFoundException)
{
}
var worker = new BackgroundWorker();
worker.DoWork += (s, we) => {
if (process != null)
{
process.WaitForExit();
try
{
File.Delete(tempFileName);
}
catch (IOException)
{
}
}
};
worker.RunWorkerAsync();
Unfortunately, Process.Start returns null if a process is not started, but a running one is used (new tab is opened in Google Chrome). So I can't wait for that process to exit.
So, a general question is: how to do the task? How to show a temporary HTML file to a user and delete it after viewing?
If you use ProcessStartInfo and set UseShellExecute then you can start the user's default browser by "running" the HTML directly like you're trying to do now. I haven't tried it, but it should give you a Process back to determine when the user has closed the browser.
I would still prepare for a bunch of edge cases you have no control over. Such as if they leave the browser open but close the app that's watching the browser. At that point do you let the browser stay alive? Do you kill it? When do you delete the HTML file? It might be better to use the Web Browser control. Then you don't even have to worry about other processes or browser compatibility. You can even stream the HTML contents to the control and there is no file to delete later.
You can force a new browser instance, by first figuring out the default browser, and executing it manually:
public Process launchBrowser(string url)
{
string browserName = "iexplore.exe";
using (RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"))
{
if (userChoiceKey != null)
{
object progIdValue = userChoiceKey.GetValue("Progid");
if (progIdValue != null)
{
if(progIdValue.ToString().ToLower().Contains("chrome"))
browserName = "chrome.exe";
else if(progIdValue.ToString().ToLower().Contains("firefox"))
browserName = "firefox.exe";
else if (progIdValue.ToString().ToLower().Contains("safari"))
browserName = "safari.exe";
else if (progIdValue.ToString().ToLower().Contains("opera"))
browserName = "opera.exe";
}
}
}
return Process.Start(new ProcessStartInfo(browserName, url));
}
Then you can get a handle to the process:
var process = launchBrowser("www.google.com");
process.WaitForExit();
try
{
//Do whatever
}
catch (IOException)
{
}
You can also read the html content into a Memory Stream or into a string variable using WebClient, and after close the Stream or WebClient, file will be released, ready to be deleted, as you no longer need it.
Them you have the html content in memory, just send it to browser.
Here some example if you need:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/060ea8e0-cc63-44a3-b0dc-b531c29b8a0f/read-html-content-using-cnet?forum=csharpgeneral
Hope it helps.

How to dowload/upload file onto a users onedrive

I am in a Highschool club where we create windows store apps. I am in charge of the code that allows the user to either download files from their online onedrive storage, or upload files. So far I have successfully logged the user in and gained access to onedrive and display the users name with the following code:
private async void LoadProfile()
{
bool connected = false;
string text = "No Error:";
try
{
var authClient = new LiveAuthClient();
LiveLoginResult result = await authClient.LoginAsync(new List<string>() {"wl.signin", "wl.skydrive"});
if (result.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
var connectClient = new LiveConnectClient(result.Session);
var meResult = await connectClient.GetAsync("me");
dynamic meData = meResult.Result;
Textblock_profilename.Text = meData.name;
}
}
catch (LiveAuthException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
catch (LiveConnectException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
if (text[0].ToString() != "N")
{
var dialog = new Windows.UI.Popups.MessageDialog(text);
await dialog.ShowAsync();
}
}
I gained the code from the following MSDN tutorial: http://msdn.microsoft.com/en-us/library/dn631823.aspx
However when I try to follow the next step, downloading and uploading files, I cannot get it to work. Right now I am just trying to press a button, and have the code download a test file:
private async void Button_downloadFile_Click(object sender, RoutedEventArgs e)
{
try
{
LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync("skydrive/documents/enter_path");
var result = await operation.StartAsync();
//DO SOMETHING WITH RESULT HERE
}
catch
{
// Handle any errors.
}
}
However this code throws the following errors:
This is straight from the MSDN tutorial, and can't figure out how to fix the error. My best guess is I'm missing a "using" statement, but can't figure out what I am missing. Thanks for any and all help!
Make sure you're updated to use the Live SDK 5.6 binary. Be sure to let us know if you have any other problems with OneDrive integration!

Categories