2013-02-26 26 views
0

我的應用程序是MVC3 C#;我使用JSON使用填充2個dropdownlists如下:文件名 - asp.net MVC3數組

public ActionResult CheckWord(string cword) 
    { 
     try 
     { 
      List<string[]> arrayList = new List<string[]>(); 
      List<string[]> stateList = new List<string[]>(); 
      // 
      List<string[]> fileList = new List<string[]>(); 
      // 
      string[] filePaths = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath("/Video"), "*.srt"); 
      string[] fnList = new string[filePaths.Length]; 
      for (int i = 0; i < fnList.Length; ++i) 
      { 
       FileInfo fi = new FileInfo(filePaths[i]); 
       fnList[i] = fi.Name.Substring(0, fi.Name.LastIndexOf(".srt")); 

      } 
      int nFiles = filePaths.Length; 
      string cacheline = ""; 
      string line; 

      for (int i = 0; i < nFiles; ++i) 
      { 
       StreamReader file = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("/Video/" + fnList[i] + ".srt")); 

       List<string> lines = new List<string>(); 
       List<string> statments = new List<string>(); 
       // 
       List<string> fnames = new List<string>(); 
       // 
       while ((line = file.ReadLine()) != null) 
       { 
        if (line.Contains(cword)) 
        { 
         statments.Add(line); 
        //  fnames.Add(file); 
         lines.Add(cacheline); 
        } 
        cacheline = line; 
       } 
       file.Close(); 
       var array = lines.ToArray(); 
       arrayList.Add(array); 
       stateList.Add(statments.ToArray()); 
      } 

      return Json(new { success = true, fnList = fnList, arrayList = arrayList.ToArray(), stateList = stateList.ToArray() }); 
     } 
     catch { } 
     return Json(new { success = false }); 
    } 

我檢查如果一組文件中是否存在一個字;然後在一個下拉列表中顯示文件的名稱,並在另一個下拉列表中顯示來自每個文件的行。它工作正常,但它給了我所有文件的列表,因爲我正在發送fnlist。不過,我試圖只顯示包含該單詞的文件;我無法從StreamReader獲取文件名並將其添加到數組fileList。我會很感激你的建議,在此先感謝。

回答

0

不知道你正在尋找什麼,但因爲你是從文件名創建StreamReader的,爲什麼沒有在文件名後面單獨的變量,並使用它:

var fileName = System.Web.HttpContext.Current.Server.MapPath(
    "/Video/" + fnList[i] + ".srt"); 
StreamReader file = new StreamReader(fileName); 
1

已經這麼多的名單!爲什麼不是其他?你已經打開帶有迴路的範圍內fnList[i]文件,所以...

List<string[]> results = new List<string[]>(); 
.... 
while ((line = file.ReadLine()) != null) { 
    if (line.Contains(cword)) { 
    results.Add(fnList[i]); 
    break; // optional, if possible, but if you need to continue check for dupes 
    } 
} 
.... 
return Json(new { 
    success = true, 
    fnList = results.ToArray(), 
    arrayList = arrayList.ToArray(), 
    stateList = stateList.ToArray() 
}); 
+0

感謝格蘭特,因爲我不是有經驗的;我如何根據你的答案添加arrayList和stateList。謝謝 – hncl 2013-02-26 22:46:21

1

就是System.IO.StreamReader文件=新就是System.IO.StreamReader( 「SETUP.TXT」);

後來,我們想打印的文件的名稱正在使用流讀取。 例如,如果有錯誤,我想顯示「讀取文件錯誤:‘名’」的消息框

MessageBox.Show("Error loading " + ((FileStream)file.BaseStream).Name);