2011-06-02 40 views
5

Not Defteri:Not defteri değerini alın ve C# dizesinin içine koyun?

Hello world! 

C# koyup dizeye dönüştürmek edeceğiz nasıl ..?

Şimdiye kadar, not defteri yolunu alıyorum.

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

beni Lütfen tavsiye .. Ben Sen kullanarak metin okuyabilirsiniz .. Bu konuda aşina değilim StreamReader ait tnx

+2

nasıl not defterinde OLUŞTURULDU bir dosyayı OKUYUN isteyen var mı? – n8wrl

cevap

7

aşağıda gösterildiği gibi dosyayı okumak File.ReadAllText() yöntemi:

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

Bu doğru değil, File.Exists çağrısı arasında bir yarış koşulu var ve aslında dosyayı okuyorsunuz. Bu süre içinde dosya silinirse, çözümünüz çökecektir. –

+0

@Greg D, bu biraz nitpicky, sence de öyle değil mi? Bu sorunun, kodun bu kurşun geçirmez olması gerektiğini düşündüğünüz bir şey var mı? –

+0

@Greg D, ikinci düşüncede, [burada cevabınız] ile karşılaştım (http://stackoverflow.com/questions/4509415/check-whether-a-folder-exists-in-a-path-in-c/ 4509517 # 4509517) ve bunun gibi çok. Teşekkürler! Cevabımı güncelledim. (Yine de yine de aşağı çekmeye katılmıyorum :) –

5

yapmak kullanımı ve

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

dosyanın içeriğini, örneğin okumak gerekir:

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

Veya basitçe mümkün olduğunca: StreamReader çağrıldığında @ kullanılmaz bu örnekte

return File.ReadAllText(path); 
3

Reading From a Text File (Visual C#), yazdığınız ancak zaman Visual Studio'daki kod, her bir \

için aşağıdaki hatayı verecektir

Tanınmayan çıkış sırası

size yol dizesinin başında olduğunu @" önce yazabilir Bu hatayı kaçmak için. @ yazmasak bile \\ kullanıyorsak, bu hatayı vermediğini de belirtmiştim.

// 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

onay bu örnek:

// 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(); 
İlgili konular