我在foreach
中有两个用于用户名和密码的变量,我想设置为全局变量,但我不知道怎么做?
我尝试使用此代码但是,当我尝试使用此变量替换带有用户名和密码的字符串时,我会收到消息:
Use of unsigned local variable 'username'.
Use of unsigned local variable 'password'.
代码:
public static void Main()
{
string[] lineOfContents = File.ReadAllLines(@"C:\\M\send.txt");
string username;
string password;
foreach (var line in lineOfContents)
{
string[] tokens = line.Split(',');
string user = tokens[0];
string pass = tokens[1];
username = user;
password = pass;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://199.199.199.199/Plovdiv.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(username, password);
答案 0 :(得分:1)
编译器不知道循环是否会执行,这就是为什么它会显示这样的警告,即,如果循环跳过迭代,循环可能执行也可能不执行({{1} }为null或没有值)然后你的局部变量lineOfContents
和username
将不会被初始化并导致异常,以避免你必须用一些默认值初始化它们,所以声明将如下所示:
password
答案 1 :(得分:1)
您可以在username
循环内为password
和foreach
分配值,但是编译器不知道lineOfContents
是否为空,当您到达时到request.Credentials = new NetworkCredential(username, password);
变量将具有任何值。你需要初始化它们
string username = string.Empty;
string password = string.Empty;
答案 2 :(得分:1)
您当前的代码逻辑错误:
C:\M\send.txt
文件为空怎么办?foreach
根本不循环,username
,password
将包含垃圾 username
,password
。如果您想保留现有逻辑(解析并分配文件的最后一行):
public static void Main()
{
var line = File
.ReadLines(@"C:\\M\send.txt") // We don't want All lines to be in memory
.LastOrDefault();
string username = ""; // or null
string password = ""; // or null
if (line != null)
{
string[] tokens = line.Split(',');
string user = tokens[0];
string pass = tokens[1];
username = user;
password = pass;
}
//TODO: you may want to add "else" here (i.e. the file is empty case)