2011-06-02 43 views
5

記事本:獲取記事本的值並將其放入c#字符串中?

Hello world! 

如何我把它在C#中,並轉換成字符串..?

到目前爲止,我正在獲取記事本的路徑。

string notepad = @"c:\oasis\B1.text"; //this must be Hello world 

請諮詢我..我不是這個熟悉.. TNX

+2

你問如何閱讀記事本創建的文件? – n8wrl 2011-06-02 21:01:30

回答

7

可以使用閱讀的文本File.ReadAllText()方法:

public static void Main() 
    { 
     string path = @"c:\oasis\B1.txt"; 

     try { 

      // Open the file to read from. 
      string readText = System.IO.File.ReadAllText(path); 
      Console.WriteLine(readText); 

     } 
     catch (System.IO.FileNotFoundException fnfe) { 
      // Handle file not found. 
     } 

    } 
+0

這是不正確的,您在調用File.Exists和實際讀取文件之間存在爭用條件。如果該文件在該期間被刪除,您的解決方案將崩潰​​。 – 2011-06-03 13:25:17

+0

@Greg D,這有點挑剔,你不覺得嗎?這個問題有什麼可以讓你認爲代碼需要是防彈的嗎? – 2011-06-03 13:46:22

+0

@Greg D,第二個想法,我偶然發現[你的答案在這裏](http://stackoverflow.com/questions/4509415/check-whether-a-folder-exists-in-a-path-in-c/ 4509517#4509517)和很多。謝謝!我已經更新了我的答案。 (我仍然不同意downvote :) – 2011-06-03 14:11:50

5

化妝使用的StreamReader和讀取文件如下圖所示

string notepad = @"c:\oasis\B1.text"; 
StringBuilder sb = new StringBuilder(); 
using (StreamReader sr = new StreamReader(notepad)) 
      { 
       while (sr.Peek() >= 0) 
       { 
        sb.Append(sr.ReadLine()); 
       } 
      } 

string s = sb.ToString(); 
6

您需要閱讀的文件的內容,例如:

using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read)) 
{ 
    return reader.ReadToEnd(); 
} 

或者,儘可能地簡單:

return File.ReadAllText(path); 
3

Reading From a Text File (Visual C#),在這個例子中,當StreamReader被稱爲@沒有被使用,然而,當你寫的在Visual Studio中的代碼它會給每個以下錯誤\

無法識別的轉義序列

逃離這個錯誤,你可以寫@之前"這是在您的路徑字符串的開頭。 我還提到,即使我們不寫@,如果我們使用\\,它也不會出現此錯誤。

// Read the file as one string. 
System.IO.StreamReader myFile = new System.IO.StreamReader(@"c:\oasis\B1.text"); 
string myString = myFile.ReadToEnd(); 

myFile.Close(); 

// Display the file contents. 
Console.WriteLine(myString); 
// Suspend the screen. 
Console.ReadLine(); 
3

檢查這個例子:

// Read the file as one string. 
System.IO.StreamReader myFile = 
    new System.IO.StreamReader("c:\\test.txt"); 
string myString = myFile.ReadToEnd(); 

myFile.Close(); 

// Display the file contents. 
Console.WriteLine(myString); 
// Suspend the screen. 
Console.ReadLine(); 
相關問題