C#没有读我的输入

时间:2009-06-15 04:59:00

标签: c# .net

我试图将路径保存到我的输入变量中,但它没有读取我的输入!我正在调试并完全跳过这条线!

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中调用此函数... 我的目标仍然是尝试将文件的内容读入数组。

这不是家庭作业! =)

7 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:2)

您可能想尝试Console.ReadLine()。

实际上,您正在读取用户输入的第二个字符,并将其视为路径名。

答案 2 :(得分: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);
    }

答案 3 :(得分:0)

您确定要使用Console.Read吗?它将从输入中读取下一个字符(即1个字符)。如果您改为使用Console.ReadLine,它将读取一整行。

此外,在上面的代码中GetLines只包含输入的第二个字符,如果我正确解释它(第二个Console.Read行将替换GetLines变量的内容)。

答案 4 :(得分:0)

Console.Readline()可能就是您所需要的。 Console.Read()读取一个字符。

此外,您的while循环有问题。 char永远不会为null,因为它是值类型。

答案 5 :(得分: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(),它的行为更直观。

答案 6 :(得分:0)

您可以使用Console.Read()实现目标。 请阅读http://msdn.microsoft.com/en-us/library/system.console.read.aspx

相关问题