Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# store a string variable to a text file .txt

  1. How can i store the contents of a string variable to a text file ?

  2. How can i search in a string variable for specific text for example find if the word book is in the string?

like image 608
jayt csharp Avatar asked Jun 02 '11 20:06

jayt csharp


3 Answers

To save the file to text you can do:

System.IO.File.WriteAllText("C:\your_path\your_file", Your_contents);

To Search for something in the string:

var position = Your_string.IndexOf("Book");

If position equals -1 then what you are searching for isn't there.

like image 116
kemiller2002 Avatar answered Oct 13 '22 20:10

kemiller2002


In the off chance you are actually stumped on where to find this information, it's as simple as:

System.IO.File.WriteAllText(myPathToTheFile, myStringToWrite);

To find a string within another string, you would simply do this:

myString.Contains(someOtherString); // boolean
myString.IndexOf(someOtherString); // find the 0 based index of the target string
like image 6
Tejs Avatar answered Oct 13 '22 21:10

Tejs


File.WriteAllText("MyFile.txt", myString); // Write all string to file
var wordBookIndex = myString.IndexOf("book"); // If the string is found, index != -1
like image 6
Teoman Soygul Avatar answered Oct 13 '22 19:10

Teoman Soygul