我是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