我是C#的新手,我试图根据txt文件的内容实现button.visible true/false。迄今为止我写的所有东西都是不稳定的。这是为主对话框中的Winform独立应用程序。显示基于登录比较的按钮
在理想的世界里,它似乎应该更简单。我希望代码打开Permissions.txt
,我知道我正在成功访问,因为MessageBox
将在列表中显示名字,并将Environment.UserName
与.txt
文件中的所有名称进行比较。一旦显示按钮,它将打开一个新的对话框。
任何人都愿意教新人。我一直在寻找一段时间,但我没有看到它。
我也试过用File.Readlines
没有成功。
非常感谢您提供任何帮助。
弗兰克Pytel
public void hideWidget()
{
//gets the users login name from the system
string newName = userNameOnly();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(dataFolder + "\\Permissions.txt");
//This next bit called Original Code works on my local when I access it, when accessed from a server, but not for other users.
//Original code
//while ((line = file.ReadLine()) != null)
//{
// if (line == newName)
// {
// WidgetForm.Visible = true;
// }
// else
// {
// WidgetForm.Visible = false;
// }
// //MessageBox.Show(line);
// counter++;
//}
//file.Close();
//This is where I am at currently. Again it's not picking up all of the names in the .txt file.
while (file.ReadLine() != null)
{
//string line;
string line = file.ReadLine();
if (newName == file.ReadLine())
{
WidgetForm.Visible = false;
}
else
{
WidgetForm.Visible = true;
}
int counter = 0;
//MessageBox.Show(line);
//MessageBox.Show(file.ReadLine());
counter ++;
}
//file.Close();
}
EDITED ....
此外,如果有任何人可能可以解释如何串线;正在设置为我的用户名。这是应该如何设置,但我从来没有告诉它在原代码中的行==新名称。我认为这就是While
的目的。检查看看它们是否相等。
FINAL EDIT。
这是我得到的工作。谢谢@Bedford。
这部分直接去下面Form1类
string[] lines = File.ReadAllLines(dataFolder + "\\Permissions.txt");
这是hideWidget()按钮
public void hideWidget()
{
//Make all userNames available to the logic
string newName = userNameOnly();
//variable to decide if userExists is true/false
bool userExists;
//Loop through all of the userNames in the file and see if it matches the userName login
while (lines != null)
{
//Decide to make the button available if userExists does exist in the file
if (lines != null)
{
userExists = lines.Any(ln => ln == newName);
WidgetForm.Visible = userExists;
}
//Do nothing if the userName does not match anyone in the Permissions.txt file. The button default Visible is false
else
{
}
return;
}
}
我张贴这个片段,以便其他人可以从中受益背后的逻辑。再次感谢@Bedford。这个NEWB真的很感谢帮助。 HAGD! :-)
要始终使用'Path.Combine'。在内部它会弄清楚参数是以反斜杠开始还是以反斜杠结尾,并将它们正确地结合起来。 – 2014-09-18 17:09:12
@muffin我做过的人' internal static string appPath = System.Windows.Forms.Application.StartupPath; 内部静态字符串dataFolder = System.IO.Path.Combine(appPath,“Data”); 内部静态字符串reportFolder = System.IO.Path.Combine(appPath,“Report”); 内部静态字符串weeklyFolder = System.IO.Path.Combine(appPath,“Weekly”); ' – 2014-09-18 17:25:01
我对此很陌生。我希望我做了正确的内部结合? – 2014-09-18 17:26:00