2013-02-26 43 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);