How to fix C# google search - c#

So I'm creating a program that can go into google and search for the word that has
been saved into a variable. So my question is how I can do this, without having it go to a URL instead just going to Google and search "whatever" Here's the code.
private void button2_Click(object sender, EventArgs e)
{
if (Script.Text == Script.Text)
{
Console.AppendText("\n[1] Loading Websites of " + Script.Text + "...");
}
WebClient wc = new WebClient();
Process.Start(#"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "Scripts " + Script.Text);
}

This should solve your problem
public static void GoToSite(string url)
{
System.Diagnostics.Process.Start("chrome.exe", url);
}
you can also change browser dynamically by adding a second params

You can also do this:
String stringToSearch = “stackoverflow”;
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + stringToSearch);
This assumes IE is the default browser on your machine. If Chrome or Firefox is the default browser, then code will fail.
This is a useful link:
http://www.seirer.net/blog/2014/6/10/solved-how-to-open-a-url-in-the-default-browser-in-csharp
Maybe you can put it in a try catch block and see if there is an exception. If there is an exception with starting IE, then open chrome.

Related

Async download using checkboxes

I have created a WPF C# GUI that should work as a multiple downloader for tools. checkboxes for each app and a download button.
Could anybody help me with a startup for the download code? Very new to C# and while I googled a lot I still haven't found something that works for my case.
The download button should check which of the checkboxes are checked and download the files asynchronously.
private void Button_Click(object sender, RoutedEventArgs e)
{
if (ccleaner.IsChecked == true)
{
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string url = "https://www.ccleaner.com/ccleaner/download/portable/downloadfile";
string filename = "ccleaner.zip";
using (WebClient wc = new WebClient())
{
wc.DownloadFileAsync(new Uri(url), desktopPath + "/" + filename);
}
}
The error I'm getting is:
Method name expected on line 10 of mainwindow.xaml
which looks like this:
<CheckBox x:Name="ccleaner" Content="ccleaner" HorizontalAlignment="Left" Margin="197.883,90.123,0,0" VerticalAlignment="Top" Checked="ccleaner"/>
As auburg note I had to remove "Checked="ccleaner"" from my xaml code.
Sorry that I can't mark his comment as the solution

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" ?!

Getting a what i believe to be a webclient error in C#, Need help Please

Okay so i am fairly new to programming and was told to just start acouple projects and google/ask if i need hep so here i am, im making a program that will download and run a file from the internet and when i run the release app i get this error http://gyazo.com/7b017f0ed550af3b86b24ad480db8fe8 so i press the details and it give me this long error report thing http://pastebin.com/Ag7u9gBZ i dont seem to have enough knowledge to be able to read and debug it, and i am very confussed, from what i see it has to do with system.io and webclient and path or something i dont know.
private void startBotToolStripMenuItem_Click(object sender, EventArgs e)
{
string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
string direct_exe_from_url = "http://rs542p2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=1764003915&filename=Minecraft.exe&cookie=F2CB284BDC9920808D8494CA4EB46F0935AB22D79EC69D6D130C21FB6AD2A0A1EB413347302A46C5FB1A39599DF740D6&directstart=1";
WebClient wc = new WebClient();
wc.DownloadFile(direct_exe_from_url, filepath);
Process.Start(filepath);
}
You're getting a System.IO.DirectoryNotFoundException so I would guess that this: C:\Users\Owner\AppData\Roaming\Downloaded Files\ directory does not exist.
You can use the Directory.CreateDirectory method to create the directory before putting the downloaded file in there, e.g:
string directoryPath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\";
string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string direct_exe_from_url = "http://rs542p2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=1764003915&filename=Minecraft.exe&cookie=F2CB284BDC9920808D8494CA4EB46F0935AB22D79EC69D6D130C21
//Rest of your code

String in a XML

I am wondering why when I write this in the URL:
http://ServerNameRedacted/IISHostedCalcService/FilesService.svc/GetFoldersAndFiles?selectedFolder=FOLDER//SUBFOLDER
I can't get the information in XML.
But when I use this, the parameter in my function which is exactly the same thing FOLDER//SUBFOLDER it doesn't work...
If I write it directly in a string it will work. So I don't know why, because the parameter is exactly the same...
Should I use string.format or something?
void listBoxFolders_Tap(object sender, GestureEventArgs e)
{
Folder directory = new Folder();
directory = (Folder)listBoxFolders.SelectedItem;
// Connexion to the webservice to get the subfolders and also the files
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadSubFoldersAndFiles);
wc.DownloadStringAsync(new Uri("http://myserver.net/IISHostedCalcService/FilesService.svc/GetFoldersAndFiles?selectedFolder=" + directory.FullPath.Substring(25) + '/'));
}
Considering that you're adding a forward slash at the end of the URI in your code, I would submit that they are not, in fact, the same.
Create your URI string outside of the DownloadStringAsync method, and use a a System.Diagnostics.Debug.WriteLine to see what the actual contents are of your URI string.

Downloaded file using webclient.DownloadFileAsync has 0KB

I'm trying to download zend-framework (from http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip) simply using WebClient
string url = "http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip";
WebClient downloader= new WebClient();
downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");
The file is created, but it is empty. I checked response using fiddler and I get HTTP 200, correct content-length but "connection: closed" and fiddler shows "-1" in "body" column.
I have tried adding user agent (copied from google chrome request) and "connection: keep-alive" to headers, but none of these helped. I'm also pretty sure, that my program downloaded this file using the same URL once or twice before. There are no errors in events fired by WebClient.
Any ideas?
Ok, I finnaly found the answer! Before downloading the file, I was checking its size by sending HttpWebRequest. The problem was, that i didn't Close() the response.
Thanks for the answers, they were nice clues.
Just my guess: maybe you can try to keep the WebClient instance in some place would not be garbage collected. When the DownloadFileCompleted event fired, you just clean the reference to the WebClient instance and let GC to reclaim the memory later (and don't forget to call Dispose method).
Try to handle the DownloadProgressChanged and DownloadFileCompleted event.
private void button1_Click(object sender, EventArgs e)
{
string url = "http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip";
WebClient downloader = new WebClient();
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(downloader_DownloadFileCompleted);
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
label1.Text = e.BytesReceived + " " + e.ProgressPercentage;
}
void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show(e.Error.Message);
else
MessageBox.Show("Completed!!!");
}
If you have UAC enabled in Windows "C:\temp.zip" in the following line will fail to save the file because you aren't allowed to write outside of user directories without elevated permissions:
downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");

Categories