2013-10-08 56 views
-1

我試圖讓我的程序從.txt中讀取代碼,然後將其讀回給我,但由於某種原因,它在編譯時崩潰了程序。有人能讓我知道我做錯了什麼嗎?謝謝! :)如何從文件中讀取?

using System; 
using System.IO; 

public class Hello1 
{ 
    public static void Main() 
    { 
     string winDir=System.Environment.GetEnvironmentVariable("windir"); 
     StreamReader reader=new StreamReader(winDir + "\\Name.txt"); 
      try {  
      do { 
         Console.WriteLine(reader.ReadLine()); 
      } 
      while(reader.Peek() != -1); 
      }  
      catch 
      { 
      Console.WriteLine("File is empty"); 
      } 
      finally 
      { 
      reader.Close(); 
      } 

    Console.ReadLine(); 
    } 
} 
+1

這不會在編譯時崩潰 – Jonesopolis

+2

我認爲你沒有權限訪問'windir \ name.txt'運行程序,並檢查 –

+0

發佈錯誤消息你會得到什麼幫助 –

回答

3

我不喜歡你的兩個簡單的原因解決方案:

1)我不喜歡得蛋白酶「時間(試行趕上)。爲避免檢查文件是否存在使用System.IO.File.Exist("YourPath")

2)使用此代碼,您尚未處理流讀取器。對於avoing這是更好地利用使用構造這樣的:using(StreamReader sr=new StreamReader(path)){ //Your code}

用例:

 string path="filePath"; 
     if (System.IO.File.Exists(path)) 
      using (System.IO.StreamReader sr = new System.IO.StreamReader(path)) 
      { 
       while (sr.Peek() > -1) 
        Console.WriteLine(sr.ReadLine()); 
      } 
     else 
      Console.WriteLine("The file not exist!"); 
+0

感謝您的建議! :) – Nathan

1

爲什麼不使用System.IO.File.ReadAllLines(WINDIR + 「\ Name.txt」)

如果你正在試圖做的一切都是在控制檯中顯示此作爲輸出,你能做到這一點非常緊湊:

private static string winDir = Environment.GetEnvironmentVariable("windir"); 
static void Main(string[] args) 
{ 
    Console.Write(File.ReadAllText(Path.Combine(winDir, "Name.txt"))); 
    Console.Read(); 
} 
+1

另外,爲什麼不'Path.Combine(winDir,「Name.txt」)' - 它更好。 – Jon

+0

我對C#很新,所以我不確定文件IO的最佳方式。你能否解釋一下我將如何使用它將值列表提取到我的程序中?謝謝:) – Nathan

+0

上面的方法利用了Using塊中的streamreader,所以它基本上可以做你想做的事,而不必全部寫出來。它返回一個表示文本文件行的字符串數組。 –

3

如果您的文件位於同一文件夾中.exe,所有你需要做的是StreamReader reader = new StreamReader("File.txt");

否則,在FILE.TXT是,把日e文件的完整路徑。就我個人而言,如果他們在同一地點,我認爲它更容易。

從那裏,如果你想讀的所有線路,並同時顯示所有的AS Console.WriteLine(reader.ReadLine());

一樣簡單,你可以爲循環做:

for (int i = 0; i < lineAmount; i++) 
{ 
    Console.WriteLine(reader.ReadLine()); 
} 
+0

謝謝你的簡單明瞭! :D – Nathan

1

使用,如果你想下面的代碼結果是字符串而不是數組。

File.ReadAllText(Path.Combine(winDir, "Name.txt")); 
0
using(var fs = new FileStream(winDir + "\\Name.txt", FileMode.Open, FileAccess.Read)) 
{ 
    using(var reader = new StreamReader(fs)) 
    { 
     // your code 
    } 
} 
0

的.NET框架有各種不同的方式來讀取文本文件。每個人都有優點和缺點......讓我們通過兩個。

首先,是一個很多其他的答案都建議:

String allTxt = File.ReadAllText(Path.Combine(winDir, "Name.txt")); 

這將整個文件讀入一個String。這將是快速和無痛的。它有一個風險雖然...如果文件足夠大,你可能會用完內存。即使你可以把整個東西存儲到內存中,它也可能足夠大,你將有分頁,並且會使你的軟件運行得非常慢。下一個選項解決這個問題。

第二個解決方案允許你用一條線同時工作,而不是整個文件加載到內存:

foreach(String line in File.ReadLines(Path.Combine(winDir, "Name.txt"))) 
    // Do Work with the single line. 
    Console.WriteLine(line); 

,因爲它會做的工作更多的時候這種解決方案可能需要較長的時間的文件與文件的內容...但是,它將防止尷尬的內存錯誤。

我傾向於採用第二種解決方案,但僅僅是因爲我對加載巨大的Strings進入記憶猶豫不決。