例如:如果文本文件具有蘋果 - Messagebox.Show("This word is exist");
如何去閱讀一個文本文件,並自動保存在c#
其他
Messagebox.Show("The word does not exist!");
,如果沒有這些詞語的文本文件將自動保存 並自動在文本文件中不存在新的文本行。
例如:如果文本文件具有蘋果 - Messagebox.Show("This word is exist");
如何去閱讀一個文本文件,並自動保存在c#
其他
Messagebox.Show("The word does not exist!");
,如果沒有這些詞語的文本文件將自動保存 並自動在文本文件中不存在新的文本行。
讀取所有text
string fileText = File.ReadAllText("filePath");
if (fileText.Contains("apple"))
{
Messagebox.Show("This word is exist");
}
else
{
Messagebox.Show("The word does not exist!");
File.AppendAllText(@"filePAth", "The word does not exixt in the text file" + Environment.NewLine);
}
謝謝..全部2回答很好。 – user2704975
方式一:
要讀取一個文件,你必須在C#中使用TextReader
:
TextReader reader = File.OpenText(@"YOUR PATH HERE");
創建TextReader
後-object你可以閱讀的整個文本文件通過:
string text = reader.ReadToEnd();
後您閱讀文件,你可以關閉TextReader
:
reader.Close();
另一種方式(無TextReader
)
您可以使用File.ReadAllText(@"YOUR PATH HERE");
string text = File.ReadAllText(@"YOUR PATH HERE");
要搜索string
或文本一個單詞,使用string.Contains("your word here");
這將返回一個bool
是否字符串con含有雜質的單詞或不:
bool contains = string.Contains("your word here");
根據contains
的值,您現在可以顯示MessageBox
。
我總是建議使用using
當你或於流TextReaders /作家的作品,所以你不必處理處置和沖洗/關閉讀/寫:
using(TextReader reader = File.OpenText(@"YOUR PATH HERE")){
string text = reader.ReadToEnd();
} //No closing needed here (close will automatically be called, when the object gets disposed
您可以使用File.ReadAllText(...);如果您將整個內容讀入內存...... – LunicLynx
自2.0以來就存在 - > http: //msdn.microsoft.com/en-us/library/system.io.file.readalltext(v=vs.80).aspx – LunicLynx
+ 1,謝謝...... – user2704975
你究竟要求什麼? – LunicLynx
只有你可以說你將如何閱讀文本文件等......問題在哪裏? (「問題必須描述一個特定的*問題並顯示*最小的理解*) – Sayse