2012-03-19 59 views
3

我有一個包含以下C#閱讀txt文件和數據存儲在格式化陣列

Name address phone  salary 
Jack Boston 923-433-666 10000 

所有字段由空格分隔的文本文件。

我想寫一個C#程序,這個程序應該讀取這個文本文件,然後將其存儲在格式化數組中。

我的數組如下:

address 
salary 

當過我試圖在谷歌我得到的是如何閱讀和寫在C#中的文本文件的樣子。

非常感謝您的時間。

+0

你在哪裏困惑?你有什麼嘗試?最難的部分可能會加載文件。 – Jetti 2012-03-19 20:16:33

+4

如果你能控制它,我認爲空間不會產生很好的分隔符。你可能想改變它。 – CAbbott 2012-03-19 20:16:49

+0

我能夠讀取文件,但不知道加載...因爲加載文件我想第二(地址)和第四字段(工資)。 – 2012-03-19 20:18:51

回答

6

可以使用File.ReadAllLines方法將文件加載到數組中。然後,您可以使用for循環遍歷這些行,並使用字符串類型的Split方法將每行分隔到另一個數組中,並將這些值存儲在格式化數組中。

喜歡的東西:

static void Main(string[] args) 
    { 
     var lines = File.ReadAllLines("filename.txt"); 

     for (int i = 0; i < lines.Length; i++) 
     { 
      var fields = lines[i].Split(' '); 
     } 
    } 
+0

非常感謝你! – 2012-03-19 20:36:19

+0

有幫助,謝謝! – 2015-11-04 15:18:04

2

不要重新發明輪子。可以使用例如fast csv reader,您可以指定您需要的delimeter

互聯網上有很多其他人都喜歡這樣,只要搜索並選擇一個適合您的需求。

1

這個答案假設你不知道有多少空白是在給定的線每個字符串之間。

// Method to split a line into a string array separated by whitespace 
private string[] Splitter(string input) 
{ 
    return Regex.Split(intput, @"\W+"); 
} 


// Another code snippet to read the file and break the lines into arrays 
// of strings and store the arrays in a list. 
List<String[]> arrayList = new List<String[]>(); 

using (FileStream fStream = File.OpenRead(@"C:\SomeDirectory\SomeFile.txt")) 
{ 
    using(TextReader reader = new StreamReader(fStream)) 
    { 
     string line = ""; 
     while(!String.IsNullOrEmpty(line = reader.ReadLine())) 
     { 
      arrayList.Add(Splitter(line)); 
     } 
    } 
}