2017-04-08 36 views
1

我有一個問題,需要我從文本文件計算合成學生標記。它給了我第一行標記的權重,下一行評估的學生數量,然後下一行是學生的標記。這種模式通過文件重複,沒有大的分離。使用StreamReader讀取其他行定義的行

爲了清楚起見,文本文件和問題是here:

我試着用下面的代碼製作與StreamReader的一個新對象:

using (StreamReader sr = new StreamReader("DATA10.txt")) { 
    blahblahblah; 
} 

DATA10.txt是在同一個文件夾中程序。

但我得到「無法從'字符串'轉換爲'System.IO.Stream'」,儘管在MSDN和其他地方的例子中使用該確切的代碼就好了。我究竟做錯了什麼?

最後我會做的是從第二行取值並使用streamreader讀取這些行數。然後在下一組數據上重複整個過程。

我真的不認爲它是這個問題的重複,並且這裏的答案以更容易理解的方式表達。

+0

在您的代碼段,你正在錯過')'。應該是'使用(StreamReader sr =新的StreamReader(「DATA10.txt」))' –

+0

對不起,我已經習慣了VS爲我添加大括號。我一直在使用你指出的適當的線。抱歉。 – James

+0

你把這個文件放在.exe文件的位置嗎? – titol

回答

0

StreamReader是假設採取在流作爲其參數也可以將Stream作爲參數,並且還必須指定FileMode

相反,嘗試這樣的事:

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

    try 
    {   
     using (FileStream fs = new FileStream(path, FileMode.Open)) 
     { 
      using (StreamReader sr = new StreamReader(fs)) 
      { 
       //blahblah  
      } 
     } 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine("The process failed: {0}", e.ToString()); 
    } 
} 

MSDN Reference

+1

非常感謝。我是C#的新手,我在大約一個月的時間裏參加了一場比賽。這一切都從這裏看上去:) – James

0

,還必須設置的「DATA10.txt」「複製到輸出目錄」屬性在解決方案資源管理「一直拷貝」

using System; 
    using System.Collections.Generic; 
    using System.IO; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 

    namespace _07___ReadTextFileWhile 
    { 
     class Program 
     { 
      static void Main(string[] args) 
      { 
       StreamReader myReader = new StreamReader("DATA10.txt"); 

       string line = ""; 

       while (line != null) 
       { 
        line = myReader.ReadLine(); 
        if (line != null) 
         Console.WriteLine(line); 
       } 

       myReader.Close(); 
       Console.ReadKey(); 

      } 
     } 
    } 

enter image description here

+0

它仍然給我完全相同的錯誤; 「無法從'字符串'轉換爲'System.IO.Stream'」 – James

+0

你可以分享「DATA10.txt」文件嗎? –

+0

對不起,我會上傳文件並編輯帖子。我忘了它沒有包含在我鏈接的文件中。 已編輯。 – James

相關問題