C#将字符串变量存储到文本文件.txt中

时间:2011-06-02 20:23:34

标签: c# string text store text-files

  1. 如何将字符串变量的内容存储到文本文件中?

  2. 如何在字符串变量中搜索特定文本,例如查找单词簿是否在字符串中?

5 个答案:

答案 0 :(得分:19)

要将文件保存为文本,您可以执行以下操作:

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

要搜索字符串中的内容:

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

如果position等于-1,那么你要搜索的内容就不存在了。

答案 1 :(得分:6)

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

答案 2 :(得分:6)

如果有机会,你实际上难以找到这些信息的位置,它很简单:

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

要在另一个字符串中查找字符串,您只需执行以下操作:

myString.Contains(someOtherString); // boolean
myString.IndexOf(someOtherString); // find the 0 based index of the target string

答案 3 :(得分:1)

System.IO命名空间有文件(和其他)IO的各种方法和类,这个可以很容易地达到你的目的:

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

至于在单个字符串内搜索,请使用String.IndexOf:

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

答案 4 :(得分:0)

回答1个问题

使用 System.IO命名空间,因为没有类可用于文件中的文本

回答2个问题

您可以使用正则表达式或使用 IndexOf 函数来搜索字符串中的特定单词