2015-02-09 88 views
-2

1 - 我有我的一些形式变量:如何读取文本文件行变量而不是文本

string BE1835 = "A"; 
string WB5884 = "B"; 
string S49807 = "C"; 
string D35950 = "D"; 

2 - 我有文本文件中含有较多的线路为:

line1 
BE1835 
S49807 
line4 
line5 

3-我使用该代码来读取文本文件

int counter = 0; 
    string line; 

    // Read the file and display it line by line. 
    System.IO.StreamReader file = 
     new System.IO.StreamReader(@JSS_File_Path_01); 
    while ((line = file.ReadLine()) != null) 
    { 
     //read line 3,6,7,8,10 
     if (counter == 1 || counter == 2) 
     { 
      final_cons_Code += line; 
     } 

     counter++; 
    } 

    file.Close(); 


    label4.Text = final_cons_Code; 

5-结果:BE1835S49807

现在我去的结果是AC不BE1835S49807

谢谢

+3

,则不应使用您的变量名称与您正在比较的内容。使用字典进行适当的查找。 – Cyral 2015-02-09 23:17:53

+0

文件中内容的'Delimiter'是什么??我会'谷歌string.Split()'方法以及'File.ReadAllText()'方法'System.IO'类 – MethodMan 2015-02-09 23:22:04

回答

1

更新时间:

// declare it 

var variables = new Dictionary<string, string>(); 

// populate it 

variables.Add("BE1835", "A"); 
variables.Add("WB5884", "B"); 
variables.Add("S49807", "C"); 
variables.Add("D35950", "D"); 

//retrieve a value 

var alphabet = variables["BE1835"]; 

在你的使用情况,您可以做到这一点

//read line 3,6,7,8,10 
    if (counter == 1 || counter == 2) 
    { 
     final_cons_Code += variables[line]; 
    } 
+0

这是如何解决使用变量作为键来检索值而不使用某种HashMap?看看@Scyral的评论和其他评论。 – 2015-02-09 23:30:54

+0

当然枚举是另一种选择,但看看这个简化的代码,我怀疑还有更多的PO只是给这个问题的部分代码。这就是为什么我认为没有必要过度使用它。 – 2015-02-09 23:39:35

+0

谢谢你回答:我该如何解决这个错误:找不到类型或命名空间名称'Map'(你是否缺少使用指令或程序集引用?) – SunEye 2015-02-10 00:25:31