How to download http file.

  • Thread starter Thread starter Anil S
  • Start date Start date
A

Anil S

Hello,

I am trying to download the file (automatically using my program) and fileName has built in date in the file name. when ever I schedule the exe file, it does not run; does anybody have any clue why it does not run?

public static void Main(string[] args)
{
DateTime dt = DateTime.Now;
string date = dt.ToString("yyyymmdd");

string fileName = "" + date + "isolf.csv";
//Console.WriteLine(fileName);
//Console.ReadLine();
string location = "http://mis.nyiso.com/public/csv/isolf/";
//string fileName2 = args[1] + "isolf.csv";
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(location+fileName);
HttpWebResponse ws = (HttpWebResponse)wr.GetResponse();
Stream str = ws.GetResponseStream();
byte[] inBuf = new byte[100000];
int bytesToRead = (int)inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0)
{
int n = str.Read(inBuf, bytesRead, bytesToRead);
if (n == 0)
break;
bytesRead += n;
bytesToRead -= n;
}
FileStream fstr = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
str.Close();
fstr.Close();
}
 
Note that "mm" isn't months - you want "MM".

Call me lazy, but I'd just use WebClient - something like:

string file = DateTime.Today.ToString("yyyyMMdd") +
"isolf.csv";
using (WebClient client = new WebClient())
{
client.BaseAddress = "http://mis.nyiso.com/public/csv/
isolf/";
client.DownloadFile(file, file);
}

(possibly deleting the file first if it already exists)

Marc Gravell
[C# MVP]
 
Does the program not even start or it fails?
How are you scheduling it?
How are you determining it doesnt run?
Why not put some logging in it and check it the log file contains anything,
potentially log all exceptions that occur in Main by wrapping the contents in
a try catch and logging it.
 
Back
Top