Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.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# 试图读取二进制文件以连接我网站上的用户_C#_Serialization_Webforms_Binaryfiles - Fatal编程技术网

C# 试图读取二进制文件以连接我网站上的用户

C# 试图读取二进制文件以连接我网站上的用户,c#,serialization,webforms,binaryfiles,C#,Serialization,Webforms,Binaryfiles,我以前已经能够用我的C#应用程序(webforms)从bin文件中读写了。在我做了一些更改之后,我仍然可以写,但不能读取多个用户 我用了调试器。foreach循环仅统计序列化中的1个用户。即使文件中有2个用户,也只统计1个用户。这是一个静态列表。它以前起过作用。我不知道我做错了什么 ``` format = new BinaryFormatter(); Users = new List<User>(); try

我以前已经能够用我的C#应用程序(webforms)从bin文件中读写了。在我做了一些更改之后,我仍然可以写,但不能读取多个用户

我用了调试器。foreach循环仅统计序列化中的1个用户。即使文件中有2个用户,也只统计1个用户。这是一个静态列表。它以前起过作用。我不知道我做错了什么

        ``` 
        format = new BinaryFormatter();
        Users = new List<User>();

        try
        {
            flux = new FileStream(path, FileMode.Open, FileAccess.Read);
        }
        catch
        { 
            Users.Add(new User("root", "root123", "email@abc.com", "Administrator"));
            Users.Add(new User("user", "user123", "email@abc.com", "User"));
            Save(path);
        }
        finally
        {
            Users = (List<User>)format.Deserialize(flux);
            if (flux != null)
               flux.Close();
        } 

        foreach (User account in Serialization.Users)
        {
            if (account.Username == username.Text && account.Password == password.Text)
            return true;
        }
        return false;
        ```
`
格式=新的二进制格式化程序();
用户=新列表();
尝试
{
通量=新文件流(路径,FileMode.Open,FileAccess.Read);
}
抓住
{ 
添加(新用户(“根”,“根123”,“根email@abc.com“,”管理人“);
添加(新用户(“用户”、“用户123”和“email@abc.com“,”用户“);
保存(路径);
}
最后
{
用户=(列表)格式。反序列化(流量);
如果(通量!=null)
flux.Close();
} 
foreach(Serialization.Users中的用户帐户)
{
if(account.Username==Username.Text&&account.Password==Password.Text)
返回true;
}
返回false;
```

我应该能够使用第二个用户登录,但正如我提到的,foreach循环在1次迭代后停止并返回false。我不明白为什么。

我发现我的代码出了什么问题。

问题不是我的try/catch,而是新用户创建帐户时的问题。正确登录并通过断开连接返回主页后,Page_Load()不会再次读取我的二进制文件,因为我忘记在那里反序列化。

为什么要读取finally块?您应该将finally块的内容移动到try块中,就在flux=newfilestream(path,FileMode.Open,FileAccess.Read)之后;在finally中,如果(flux!=null)flux.close,则只需执行finally。我使用finally块,因为在catch块中,我会在再次读取之前写入,所以我不会将新文件流粘贴两次(在try和catch块中),而只在catch块末尾写入一次,最后反序列化。请重新阅读关于发布代码的指南。不需要显示实际代码所做的所有有趣的事情——只需要重要但可复制的部分。类似于显示可能写入2个用户的代码。您不应该以这种方式使用try-catch,不要依赖异常来了解文件是否不存在并保存它,相反,在try块中,您可以检查文件是否存在并相应地执行操作。