Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 读取文本文件中的2行乘2行_C# - Fatal编程技术网

C# 读取文本文件中的2行乘2行

C# 读取文本文件中的2行乘2行,c#,C#,假设下面的ReadUser方法正在读取文本文件中的用户和密码。问题是,它在读取前两行后不会读取文本文件的其余部分。如何解决这个问题 *编辑:如何读取文本文件中的前2行,然后再读取另外2行 public override void ReadUser() { user = base.UserID; password = base.Password; using (StreamReader sr = new StreamReader(File.Open("C:\\Users\

假设下面的ReadUser方法正在读取文本文件中的用户和密码。问题是,它在读取前两行后不会读取文本文件的其余部分。如何解决这个问题

*编辑:如何读取文本文件中的前2行,然后再读取另外2行

public override void ReadUser()
{
    user = base.UserID;
    password = base.Password;

    using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt", FileMode.Open)))
    {
        user1 = sr.ReadLine();
        password1 = sr.ReadLine();
        sr.Close();

        if (user == user1 && password == password1)
        {
            Console.WriteLine("Login Successfull");
        }
        else
        {
            Console.WriteLine("Login Failed");
        }
    }
}
简单逻辑

int currentLine = 0;
//no need use close method with using
using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt", FileMode.Open)))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        switch (++currentLine)
        {
            case 1: user1 = line; break;
            case 2: password1 = line; break;
            case 3: otherVariable = line; break;
            case 4: yetAnotherVariable = line; break;
            ......
        }
        //rest of your logic

    }
}

但是,如果出于某种原因需要将所有字符串存储在一个数组中,最好只使用

即可使用sr.Close()关闭StreamReader;在阅读了前2篇之后lines@styx因此,我只需要删除sr.Close(),然后它将继续读取文本文件中的其余行?请参阅:。顺便说一句,使用
using
语句声明了
StreamReader
,您不需要关闭该流。一旦您使用块离开
,它就会关闭并处理。另外,这个:
File.Open(“C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt”
是个坏主意。使用
Application.StartupPath
访问应用程序可执行文件当前所在的目录(部署时不在那里)。无论在何处调用
Close()
,此代码都将只读取前两行。您正在显式调用
sr.ReadLine();
两次,就是这样。为了读取文件中的所有行,您需要使用循环或读取所有行的方法。@Jimi,知道如何使用application.startupPath吗?知道从文本文件中读取两行然后再读取文本文件中的另外两行吗???对不起,新手here@FatassBulky你可以继续u的逻辑sing i variable(我对应于您正在阅读的行号)@FatassBulky编辑了我的答案,以便您更好地理解