jayt csharp
jayt csharp

Reputation: 455

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?

Upvotes: 10

Views: 40504

Answers (5)

Pranay Rana
Pranay Rana

Reputation: 176956

answer to 1 question

make use of System.IO namespace in that there are not class availabe to wirte the text in file

answer to 2 question

you can use Regular expression or make use of IndexOf function to serach specific word in string

Upvotes: 0

asawyer
asawyer

Reputation: 17808

System.IO namespace has various methods and classes for file (and other) IO, this one may serve your purpose easily:

http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx

As for searching inside a single string, use String.IndexOf:

http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115538

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.

Upvotes: 23

Teoman Soygul
Teoman Soygul

Reputation: 25742

File.WriteAllText("MyFile.txt", myString); // Write all string to file
var wordBookIndex = myString.IndexOf("book"); // If the string is found, index != -1

Upvotes: 6

Tejs
Tejs

Reputation: 41256

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

Upvotes: 6

Related Questions