2009-07-17 86 views
2

我正在寫這個小程序從文本文件中提取任意數量的電子郵件地址。我收到兩個錯誤,「使用未分配的本地變量」。我不知道爲什麼。簡單的C#錯誤幫助

static void Main(string[] args) 
{ 
string InputPath = @"C:\Temp\excel.txt"; 
string OutputPath = @"C:\Temp\emails.txt"; 
string EmailRegex = @"^(?:[a-zA-Z0-9_'^&/+-])+(?:\.(?:[a-zA-Z0-9_'^&/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)$"; 
string Text = String.Empty; 
StringBuilder Output; 
List<string> Emails; 

using (TextReader tr = new StreamReader(InputPath)) 
{ 
    Text = tr.ReadToEnd(); 
} 

MatchCollection Matches = Regex.Matches(Text,EmailRegex); 

foreach (Match m in Matches) 
{ 
    Emails.Add(m.ToString().Trim()); // one error is here 
} 

foreach (String s in Emails) 
{ 
    Output.Append(s + ","); // the other error is here 
} 

using (TextWriter tw = new StreamWriter(OutputPath)) 
{ 
    tw.Write(Output.ToString()); 
} 
} 

對不起格式化......我有點時間緊迫!

編輯:WOW。我是一個白癡 - 一定是因爲我時間緊迫!!!!

+1

你想讓我們爲你「懲罰」你是個「白癡?」嗎? ;)順便說一句,按下時間,慢下來!這是你真正的錯誤。 (和不,你是不是一個白癡,我們都犯了這個錯誤至少一次) – 2009-07-17 13:31:43

回答

21

您未初始化StringBuilder和List。

StringBuilder Output = new StringBuilder(); 
List<string> Emails = new List<String>(); 
9

的問題是在這裏:

StringBuilder Output; 
List<string> Emails; 

您還沒有初始化EmailsOutput。嘗試:

StringBuilder Output = new StringBuilder(); 
List<string> Emails = new List<string>(); 
8

你是不是創建一個Stringbuilder或電子郵件列表:

StringBuilder Output = new StringBuilder(); 
List<string> Emails = new List<string>(); 
8

你的「輸出」和「列表」變量不是與對象實例分配。更改:

StringBuilder Output; 
List<string> Emails; 

StringBuilder Output = new StringBuilder(); 
List<string> Emails = new List<string>(); 
4

您必須使用 「新」 來初始化電子郵件和輸出對象。基本上有:

StringBuilder Output = new StringBuilder(); 
List<string> Emails = new List<string>(); 
1

正如許多人所說,錯誤來自你沒有創建的對象。

但是,爲什麼你將電子郵件地址存儲在臨時列表中,然後將它們放入一個臨時字符串中,然後將其寫入文件?直接寫入文件:

static void Main(string[] args) { 

    string InputPath = @"C:\Temp\excel.txt"; 
    string OutputPath = @"C:\Temp\emails.txt"; 
    string EmailRegex = @"^(?:[a-zA-Z0-9_'^&amp;/+-])+(?:\.(?:[a-zA-Z0-9_'^&amp;/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)$"; 

    using (TextWriter tw = new StreamWriter(OutputPath)) 
     foreach (Match m in Regex.Matches(File.ReadAllText(InputPath), EmailRegex)) { 
     tw.Write(m.Value); 
     tw.Write(','); 
     } 
    } 
} 

注意:正則表達式似乎已經損壞了某處沿線。其中有一些&amp;,可能應該只是&個字符。