I want to ask you guys if it is possible to do the following:
Type in textbox something like this "search pluto"
and then it must search for that last word.
This is how I did it but it doens't work because when I do that
my browser opens up twice.
One with "https://www.google.be/#q="
and the other tab that opens is the word that I wrote in
the textbox. Can somebody help me out of this please?
This is the code for this:
string url = "https://www.google.be/#
if (inputTBX.Text.Contains("search ") == true)
{
inputTBX.Text.Replace("search ", "");
string URL = url += inputTBX.Text;
Process.Start(#"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
URL);
inputTBX.Clear();
}
just as a test in a simple console app I tried the following and it worked launching my default browser
var t = "pluto";
Process.Start("http://google.com/search?q=" + t);
This also works
var t = "pluto";
Process.Start("https://www.google.be/search?q=" + t);
in your case you need to get your query string to be the following
https://www.google.be/#q=pluto
your first problem is that you are trying to use the Replace method but you need to assign it into something here is a working solution of your code just tested notice the differences in what I have done
inputTBX.Test = "search pluto";
string url = "https://www.google.be/search?q=";
if (inputTBX.Contains("search "))
{
inputTBX.Text = inputTBX.Replace("search ", "");
string URL = url += inputTBX;
Process.Start(URL); // this will launch your default web browser
inputTBX.Clear();
}
since your query string has the word search in it.. you really don't need this line if (inputTBX.Contains("search ")) but if you keep it it will work with if you pass search planet pluto for example in your textbox
This part
inputTBX.Text.Replace("search ", "");
Is seriously bad, because it will fail to do its job if you have input string like this
"search research on Beethoven's work"
If you want the key phrase to be "search ", you should do this instead
inputTBX.Text.Substring(("search ").Length); //this way it will skip the "search " phrase and use the rests of the phrase for searching
As for your process with the given URL, simply do
string url = "https://www.google.be/#q="; //notice the q= is missing in your code shown
Process.Start(url + inputTBX.Text.Substring(("search ").Length));
Related
Console.WriteLine("What name would you like to be known as?");
string usernameforscore = Console.ReadLine();
string path = *filepath*;
File.WriteAllText(path, (usernameforscore + " " + classicscore + Environment.NewLine));
So this code is part of a game I'm making for a project, at the end of the game when you fail, I want it to save both a person's chosen username and their score (a variable saved somewhere else). I have got it to save the two to the file, however each time someone enters a new set of data, the file is overridden and only the new data is displayed.
I would like it to write a line with the name and score, then next time the code is run, it will display the new name and score on the next line, creating a high score list.
I'm using visual studio with a console program on C#
Apologies if this is a duplicate, couldn't seem to find a fix myself.
There is a method AppendAllText() rather than WriteAllText(), as below:
File.AppendAllText(#"c:\Path\filename.txt", "the text to append" + Environment.NewLine);
You can use the below method UpdateTextFile to save data to a text file.
public static void UpdateTextFile(string fileName, string content, bool doNotOverwrite = true, bool writeNewLine = true)
{
StreamWriter file = null;
using (file = new System.IO.StreamWriter(#"D:\" + fileName + ".txt", doNotOverwrite))
{
if (writeNewLine)
{
file.WriteLine(content);
}
else
file.Write(content);
file.Close();
}
}
Example of calling the method:
UpdateTextFile("FileName", "file-content", true, false);
Hope it helps.
I am using Directory.CreateDirectory(string) method to create folders, now the problem is if the user enters string as:
"C:\folder1" then it creates the folder in the respective location, fine by me.
but if he writes
"C:\\\\\\\\\\\\\\\\\\\\\\\\\folder1" it is also navigating to the same path, creates folder and not giving any error, this is a problem for me.
So in order to solve the above mentioned problem I try to do some validation before on the path and I tried with Path.GetFullPath() and other Path methods and I see:
Path.GetFullPath("C:\\\\folder1") no exception or error
Path.GetFullPath("C:\\\folder1") exception or error
somehow when the count of backslashes are in even number no exception is thrown but when the count is in odd number then exception is thrown.
How can I achieve this simple thing that when user enters path like:
C:\folder 1 valid path
C:\\\\\\folder1 invalid path
Please let me know if further details are required
Possible solution using FolderBrowserDialog - Users will not manually input the path but rather select/create it via FolderBrowserDialog.
The below code will return all the files in a folder but you can amend it to return whatever information you need.
private void Form1_Load(object sender, EventArgs e)
{
//
// This event handler was created by double-clicking the window in the designer.
// It runs on the program's startup routine.
//
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// We print the number of files found.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
Code found here
If you want to get a proper path from that, maybe you can use the following technique (in addition to what you already have, of course, this is only to remove the repeated backslashes)
Split the path using the '\' character
Remove the empty values (you can filter here the non valid
characters, etc)
Reconstruct the path string using join with the character '\' again
Something like:
pathString = "C:\\\\\\folder1";
splitString = pathString.Split('\\');
nonEmpty = splitString.Where(x => !string.IsNullOrWhiteSpace(x));
reconstructed = string.Join("\\", nonEmpty.ToArray());
Test code here: https://dotnetfiddle.net/qwVqv8
What about sanitizing the path?
char[] separator = new char[] { System.IO.Path.DirectorySeparatorChar };
string inputPath = "C:\\\\\\\folder1";
string[] chunks = inputPath.Split(separator, StringSplitOptions.RemoveEmptyEntries);
string validPath = String.Join(new string(separator), chunks);
Here is my code
private string path = Path.GetTempPath() + "Test.pdf";
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.AllThreads;
System.Windows.Forms.SendKeys.SendWait(path);
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.UIThreadOnly;
Keyboard.SendKeys("{Enter}");
There is a window explorer for opening a file. The file exists on the temp path. It sometimes works and sometimes it enter the path as :\Users\.... which means it ignores C. I am not sure what is the problem? Why it is inconsistent? Any help is appreciated.
I already tried
private string path = #"" + Path.GetTempPath() + "Test.pdf";
but it is the same (sometimes works, sometimes does not)
I added empty char before the path
private string path = #" " + Path.GetTempPath() + "Test.pdf";
But still it is the same!
I had a similar problem with Coded UI but it omitted a small number of characters randomly throughout the string. I never found out the real reason, but I got around the problem by sending the characters one at a time with a short pause between them. I use code similar to the following:
void SendKeysSlowly(string text)
{
foreach ( char s in text )
{
SendKeys(s); // Choose the appropriate send routine
System.Threading.Thread.Sleep(50); // Milliseconds, adjust as needed
}
}
Also, you should ensure the string always starts with a "C:"? You could add code of the form Assert(path.StartsWith("C:\\")); before the first ...Sendkeys call.
Try using
Path.Combine(Path.GetTempPath(), "Test.pdf")
From c#, I want to launch a process which will open a text file in any editor and automatically move cursor to a certain line number.
I can open a file using
Process.Start(#"c:\myfile.txt");
but I don't know how to move cursor at specific location in that file.
Answer with source code:
yes, I used notepad++
private void openLog() {
try {
// see if notepad++ is installed on user's machine
var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
if (nppDir != null) {
var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
var nppReadmePath = Path.Combine(yourDirectory,fileName );
var line = 20;
var sb = new StringBuilder();
sb.AppendFormat("\"{0}\" -n{1}", nppReadmePath, lineNo);
Process.Start(nppExePath, sb.ToString());
} else {
string newPath = #"\\mySharedDrive\notpad++\bin\notepad++.exe";
Process.Start(newPath, #"\\" + filePath + " -n" + lineNo); // take exe from my shared drive
}
} catch (Exception e) {
Process.Start(#"\\" + FilePath); // open using notepad
}
}
Get Notepad++, then you can do this:
var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
var nppReadmePath = Path.Combine(nppDir, "readme.txt");
var line = 20;
var sb = new StringBuilder();
sb.AppendFormat("\"{0}\" -n{1}", nppReadmePath, line);
Process.Start(nppExePath, sb.ToString());
In this example we get install path of n++ from the registry, build path to exe and readme.txt file, opens its own readme.txt file with cursor on line 20.
Using StringBuilder is more efficient than using multiple appends (explanation somewhere on SO).
The solution very heavily depends on which process/editor is opened on your system. That editor would have to have a developer API that you could use to access functionality such as setting ranges and altering the cursor position. For example, if the editor that is opened is Microsoft Word, you would use the Word Interop API to set a selection at a specific position. There is no universal way to do this in 'any editor' since each one has its own API (or no outward facing API at all).
Perhaps you are going this the wrong way. I'm not sure what you are trying to accomplish, but I think it would be alot easier to just open the text file in an editor that belongs to your application. Perhaps another form with a WYSIWYG editor control. That way you have full control on where the cursor will land in that editor. Otherwise, there are just way too many unknowns for anything feasibly workable.
So I've been racking my brain trying to figure out how to implement a "talk" function in my game. I'm new to C# programming but I've been doing as much reading and experimenting as I can with the language.
This is what I have so far:
Comm comm = new Comm();
string message = null;
if (InputBox.Text == "say " + message)
{
OutputBox.AppendText(comm.do_say(message));
}
class Comm
{
public string do_say(string message)
{
return "You say: " + message + "\n";
}
}
Now, this doesn't work. I think I know why, but I can't seem to figure out just how to redo it so it does work... I've tried to replace:
(InputBox.Text == "say " + message)
with
(InputBox.Text == "say {0}", message)
and it doesn't work either. So, now I'm out of ideas on how to make this work. I tried searching stackoverflow and google for answers but came up with nothing.
Any help or hints on how to fix it would be great!
Thanks.
You don't know what the message is in advance, right? You need to search for the "Say ", and take the rest of the string as input.
if(InputBox.Text.StartsWith("Say "))
OutputBox.Text += InputBox.Text.SubString(4);
SubString(4) will return whatever's after the first 4 characters in the string, everything after the "Say "
You seem to be looking for pattern matching here, but C# doesn't support pattern matching. In other words, simply writing
if (InputBox.Text == "say " + message)
does not automatically assign "foo" to message whenever the user types "say foo".
Instead, you should probably use regular expressions, which are implemented in C# with the Regex class. Try something like
Match m = Regex.Match(InputBox.Text, #"^say\s+(.*)$", RegexOptions.IgnoreCase);
if (m.Success)
{
OutputBox.AppendText(Comm.GetScreenoutput(m.Groups[1].Value));
}
You don't need to make do_say an instance method, so in the code above I have assumed that Comm is transformed to
static class Comm
{
public static string GetScreenOutput(string message)
{
return "You say: " + message + "\n";
}
}
This code follows the naming conventions for C# code, using Pascal case for method names.
if (InputBox.Text.ToUpper().StartsWith("SAY "))
{
OutputBox.AppendText(comm.do_say(message));
}
This will check if the user used the word say, regardless of the case used.