Skip to content

Instantly share code, notes, and snippets.

@kiichi54321
Created November 10, 2012 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiichi54321/4050547 to your computer and use it in GitHub Desktop.
Save kiichi54321/4050547 to your computer and use it in GitHub Desktop.
webからCSVファイルを読み込む便利クラス。
public static class Tool
{
public static IEnumerable<string> ReadLine(string s)
{
System.IO.StringReader sr = new System.IO.StringReader(s);
while (true)
{
if (sr.Peek() < 0) break;
yield return sr.ReadLine();
}
}
public static IEnumerable<string> WebReadLines(string url, System.Text.Encoding enc)
{
using (System.Net.WebClient wc = new System.Net.WebClient())
using (Stream st = wc.OpenRead(url))
using (StreamReader sr = new StreamReader(st, enc))
{
while (sr.Peek() > -1)
{
yield return sr.ReadLine();
}
}
}
public static IEnumerable<string> WebReadLines(string url)
{
return WebReadLines(url, System.Text.Encoding.UTF8);
}
public static IEnumerable<Dictionary<string, string>> WebReadDataCSV(string url, System.Text.Encoding enc)
{
var header = WebReadLines(url, enc).DefaultIfEmpty(string.Empty).FirstOrDefault().Split(',');
foreach (var item in WebReadLines(url, enc).Skip(1))
{
Dictionary<string, string> dic = new Dictionary<string, string>();
var d = item.Split(',');
foreach (var item2 in header)
{
dic.Add(item2, string.Empty);
}
for (int i = 0; i < Math.Min(header.Length, d.Length); i++)
{
dic[header[i]] = d[i];
}
yield return dic;
}
}
public static IEnumerable<Dictionary<string, string>> WebReadDataCSV(string url)
{
return WebReadDataCSV(url, Encoding.UTF8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment