2013-04-21 88 views
-1

我寫了下面的代碼保存在字符串數組文件名:存儲文件名稱中的字符串數組

string[] fileStore; 
private void button1_Click(object sender, EventArgs e) 
{ 
    DirectoryInfo dir1 = new DirectoryInfo(@"D:\data\"); 
    FileInfo[] files = dir1.GetFiles("*.txt", SearchOption.AllDirectories); 

    foreach (FileInfo f in files) 
    { 
     int a = 0; 
     string ss; 
     ss = f.Name; 

     try 
     { 
      fileStore[a] = ss.ToString(); 
      a++; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 
} 

但是這個代碼給出了以下異常:未設置爲一個實例

對象引用的一個對象。

+1

錯誤還指出,在特定線路PS:'ss'已經是一個字符串,沒有理由罵'的ToString()' – zerkms 2013-04-21 11:19:52

+0

那麼你是如何嘗試解決這個問題呢? – usr 2013-04-21 11:19:59

+2

filestore是'null'。 – CodesInChaos 2013-04-21 11:20:23

回答

4

filestore爲空。您可以通過filestore = new string[files.Length]進行初始化。

個人而言,我會通過filestore = files.Select(f => f.Name).ToArray()更換你的整個foreach循環。

try...catch也是荒謬的。在try部分中絕不應該有例外,除非您的程序有錯誤。如果你想要一個try...catch它應該在文件枚舉周圍,它應該只捕獲幾個IO相關的異常,而不是System.Exception

1

在聲明數組string[]你必須知道與分配數據之前的確切大小:

fileStore = filestore = new string[files.Length]; 

但也許你可以用System.Collections.Generic.List<string>取代string[]它不需要你知道數組的大小提前:

List<string> fileStore = null; 

// In function: 
if(fileStore == null){ 
    fileStore = new List<string>(); 
} else { 
    fileStore.Clear(); // Optionally remove elements collected so far 
} 

foreach (FileInfo f in files) { 
    fileStore.add(f.Name.ToString()); 
} 

// And you always can export list to array: 
string filesStoreArray[] = fileStore.ToArray(); 
相關問題