2013-08-22 32 views
-6

例如:如果文本文件具有蘋果 - Messagebox.Show("This word is exist");如何去閱讀一個文本文件,並自動保存在c#

其他

Messagebox.Show("The word does not exist!");
,如果沒有這些詞語的文本文件將自動保存 並自動在文本文件中不存在新的文本行。

+0

你究竟要求什麼? – LunicLynx

+0

只有你可以說你將如何閱讀文本文件等......問題在哪裏? (「問題必須描述一個特定的*問題並顯示*最小的理解*) – Sayse

回答

0

讀取所有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); 
    } 
+0

謝謝..全部2回答很好。 – user2704975

1

方式一:

要讀取一個文件,你必須在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 = false - >單詞不在文本中。

根據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 
+1

您可以使用File.ReadAllText(...);如果您將整個內容讀入內存...... – LunicLynx

+1

自2.0以來就存在 - > http: //msdn.microsoft.com/en-us/library/system.io.file.readalltext(v=vs.80).aspx – LunicLynx

+0

+ 1,謝謝...... – user2704975