static void Main(string[] args)
{
StreamReader reader = null;
StreamWriter writer = null;
//string fileName = @"C:\Program Files\EODdlc\DATA\NSE\EQUITIES\20070924.csv";
string fileName = DownloadBhavCopy();
if (String.IsNullOrEmpty(fileName))
{
Console.WriteLine("Couldn't download BhavCopy");
return;
}
try
{
Console.WriteLine("Converting " + fileName);
reader = new StreamReader(fileName);
writer = new StreamWriter(fileName + ".txt");
string str = reader.ReadLine();
Console.WriteLine(str);
writer.WriteLine("<ticker>,<Date>,<open>,<high>,<low>,<close>,<vol>,");
int i = 0;
StringBuilder strBuilder = new StringBuilder();
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (!str.Contains(",EQ,"))
Console.WriteLine(str);
else
{
strBuilder.Remove(0, strBuilder.Length);
++i;
string[] tempStr = str.Split(new char[] { ',' });
DateTime dateTime = DateTime.Parse(tempStr[10]);
strBuilder.Append(tempStr[0] + ",");
string dateStr = dateTime.Year
+ (dateTime.Month < 10 ?
"0" + dateTime.Month.ToString() : dateTime.Month.ToString()) +
(dateTime.Day < 10 ?
"0" + dateTime.Day.ToString() : dateTime.Day.ToString());
strBuilder.Append(dateStr + ",");
strBuilder.Append(tempStr[2] + ",");
strBuilder.Append(tempStr[3] + ",");
strBuilder.Append(tempStr[4] + ",");
strBuilder.Append(tempStr[5] + ",");
strBuilder.Append(tempStr[8] + ",");
writer.WriteLine(strBuilder.ToString());
}
}
Console.WriteLine("Total " + i + " Scrips written to the file");
writer.Flush();
Console.ReadLine();
}
finally
{
if (reader != null)
reader.Close();
if (writer != null)
writer.Close();
}
}
static string DownloadBhavCopy()
{
WebClient client = new WebClient();
string dlFile = String.Empty;
FileStream writer;
try
{
string month = monthList[ DateTime.Today.Month - 1];
string day = (DateTime.Today.Day <= 9) ? "0" + DateTime.Today.Day.ToString() :
DateTime.Today.Day.ToString(); ;
string year = DateTime.Today.Year.ToString();
Uri uri = new Uri(@"http://www.nse-india.com/content/historical/EQUITIES/2007/");
Uri tempUri = new Uri(uri, month + "/cm" + day + month + year + "bhav.csv");
Debug.WriteLine("Downloading " + tempUri.ToString());
Console.WriteLine("Downloading " + tempUri.ToString());
byte[] data = client.DownloadData(tempUri);
dlFile = Path.Combine(Path.GetTempPath()/*@"C:\Program Files\EODdlc\DATA\NSE\EQUITIES"*/, "cm" + day + month + year + "bhav.csv");
using (writer = File.Create(dlFile))
{
try
{
writer.Write(data, 0, data.Length);
}
finally
{
if (writer != null)
writer.Close();
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Message.Contains("404"))
Debug.WriteLine("FileNotFound");
dlFile = string.Empty;
}
return dlFile;
}
}