2017-06-05 37 views
0

我有兩個變量foreach用戶名和密碼,我想設置爲全局變量,但我不知道如何? 我嘗試用這個代碼,但,當我嘗試使用這個變量來代替用戶名和密碼字符串我收到消息:如何在主要方法中設置全局變量c#

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

,這是因爲你初始化變量,但沒有設置任何價值他們。你應該爲它們分配一個初始值。例如。 'string username =「」; string password =「」;' –

回答

1

編譯器不知道是否循環將執行或不執行,這就是爲什麼它會顯示這樣的警告,即循環可能執行也可能不執行,如果它跳過迭代(lineOfContents爲空或它沒有值),那麼你的局部變量usernamepassword將不會被初始化並且導致異常,以避免您必須使用它們進行初始化一些默認值,這樣的聲明是這樣的:

string username = ""; // String.Empty or some default values 
string password = ""; 
// rest of code here 
1

你賦值usernamepasswordforeach循環內,但是編譯器不知道lineOfContents不是空的,當你到達request.Credentials = new NetworkCredential(username, password);這些變量將具有任何價值。你需要初始化它們

string username = string.Empty; 
string password = string.Empty; 
+0

謝謝你們.. –

1

您當前的代碼有錯誤的邏輯:

  1. 如果C:\M\send.txt文件是foreach在所有和username不循環,password將包含垃圾
  2. 爲什麼你會遍歷整個文件?這是文件的最後一行,它將最終分配給usernamepassword

如果要保留現有的邏輯(解析並指定文件的最後一行):

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)