2009-06-15 37 views
1

我試圖將路徑保存到我的輸入變量,但它不讀取我的輸入!進行調試並完全跳過這一行!C#不能讀取我的輸入

public static void OpenFile(int FileSize) 
    { 
     char GetLines = ' '; 
     char[] FileContents = new char[FileSize]; 

     Console.WriteLine("Enter a Path Name: "); 
     GetLines = (char)Console.Read(); 
     GetLines = (char)Console.Read(); // Getting No Input Y? 

     StreamReader MyStream = File.OpenText(GetLines.ToString()); 


     while (GetLines != null) 
     { 
      Console.WriteLine(FileContents); 
      GetLines = (char)MyStream.Read(); 
     } 
     MyStream.Close(); 


    } 

其他一切正常。這個函數在Main中被調用... 我的目標仍然是嘗試將文件的內容讀入數組中。

這不是一個家庭作業! =)

+0

作爲char,GetLines不能爲null,所以while循環永遠不會結束。編譯器可能會發出警告。 – 2009-06-15 12:32:39

回答

3

爲什麼不直接使用Console.ReadLine()和MyStream.Readline()?

這裏是一個StreamReader例如:

public class ReadTextFile 
{ 
    public static int Main(string[] args) 
    { 
     Console.Write("Enter a File Path:"); 
     string fileName = Console.Readline(); 
     StreamReader reader = File.OpenText(fileName); 
     string input = reader.ReadLine(); 
     while (input != null) 
     { 
      Console.WriteLine(input); 
      input = reader.ReadLine(); 
     } 
     reader.close; 
     return 0; 
    } 
} 
0

你確定要使用Console.Read?它將從輸入中讀取下一個字符(即1個字符)。如果您改爲使用Console.ReadLine,它會讀取完整的一行。

此外,在代碼以上GetLines只包含你的輸入的第二個字符,如果我正確地解釋它(第二Console.Read線將替代GetLines變量的內容)。

2

您可能想嘗試Console.ReadLine()。

事實上,您正在讀取用戶輸入的第二個字符,並將其視爲路徑名稱。

1
public static void OpenFile(){ 
    string path; 
    while(true){ 
     Console.Write("Enter a path name: "); 
     path = Console.ReadLine(); 
     if(File.Exists(path)) 
      break; 
     Console.WriteLine("File not found"); 
    } 

    string line; 
    using(StreamReader stream = File.OpenText(path)) 
     while((line = stream.ReadLine()) != null) 
      Console.WriteLine(line); 
} 

如果你需要在一個字符串的文件的全部內容,改變功能的後者部分:

string file; 
    using(StreamReader stream = File.OpenText(path)) 
     line = stream.ReadToEnd(); 

如果你真正需要的是一個字節數組,使用:

byte[] file; 
    using(FileStream stream = File.OpenRead(path)){ 
     file = new byte[stream.Length]; 
     stream.Read(file, 0, file.Length); 
    } 
0

Console.Readline()可能是你需要的。 Console.Read()讀取單個字符。

此外,你的while循環有一個問題。 char不會爲空,因爲它是一個值類型。

0

查看Console.Read的documentation以瞭解其行爲。

假設您想輸入'a'和'b'作爲連續輸入。 Console.Read塊,如果流中沒有字符 - 它不會返回,直到用戶按下Enter鍵(此時它會添加一個依賴於操作系統的行尾分隔符(Windows的\ r \ n)。 假設您輸入a[Enter]

GetLines = (char)Console.Read(); // blocks till you press enter (since no chars to read) - contains 'a' (97) 
GetLines = (char)Console.Read(); // doesn't block reads \r (13) from the stream 
GetLines = (char)Console.Read(); // doesn't block reads \n (10) from the stream 

相反,如果你的第一個read()輸入abc[Enter],GetLines將包含A,b和C分別。

正如其他人所指出的,你可能想的ReadLine()的行爲更直觀。