2015-07-13 33 views
-1

我有這樣的代碼,螞蟻它的正常工作:C#讀取網頁價值,創造的foreach

FileNameAndSizes.Add("file1.dll", 17662); 
FileNameAndSizes.Add("file2.dll", 19019); 

但我wan't從我的網站給它(http://example.com/dll_files.ini

在我dll_files .ini:

file1.dll,17662 
file2.dll,19019 

我知道我必須使用foreach。我創造了這個代碼:

WebClient client = new WebClient(); 
Stream stream = client.OpenRead("http://example.com/dll_files.ini"); 
TextReader reader = new StreamReader(stream); 
String content = reader.ReadToEnd(); 

我wan't給從dll_files.ini和翻拍值要FileNameAndSizes.Add( 「file1.dll」,17662);文件名...

接下來是什麼?請幫助,我是C#的新手,非常感謝,P.S我不是英語 P.S.S是存在更快的方法來從Web獲得價值?因爲StreamReader的〜2秒裝載

+0

你能提供content'您是從網絡接收字符串'的內容是什麼? –

+0

在我的dll_files.ini中: file1.dll,17662 file2.dll,19019 – EvaldasL

+0

我編輯了答案,假設你有''file1.dll,17662 \ nfile2.dll,19019';'格式。嘗試一下。 –

回答

0

試試這個

 Dictionary<string, long> FileNameAndSizes = new Dictionary<string, long>(); 
     WebClient client = new WebClient(); 
     Stream stream = client.OpenRead("http://example.com/dll_files.ini"); 
     TextReader reader = new StreamReader(stream); 
     String content = reader.ReadToEnd(); 

     var splitsByLine = content.Split('\n'); //Assuming contents has "file1.dll,17662\nfile2.dll,19019"; 
     foreach (var s in splitsByLine) 
     { 
      var nameAndSize = s.Split(','); 
      FileNameAndSizes.Add(nameAndSize[0], Convert.ToInt64(nameAndSize[1])); 
     } 

穿越......

foreach (var fileNameAndSize in FileNameAndSizes) 
     { 
      var name = fileNameAndSize.Key; 
      var size = fileNameAndSize.Value;     
      //Other something ... 
     } 
+0

謝謝,但事實並非如此,我需要從我的web文件中獲取價值,並將這些「file1.dll,17662 file2.dll,19019」替換爲FileNameAndSizes.Add(「file.1」,17662); – EvaldasL

+0

@EvaldasL您的網站是否像例如'file1.dll,1214,file2.dll,4545'等那樣返回字符串? –

+0

是的,我不想創建FileNameAndSizes.Add(firstvalue); FileNameAndSizes.Add(secondvalue); etc .. // firstvalue is file1.dll,1214 // secondvalue is file2.dll,4545 – EvaldasL