VBA - save Internet file

29 nov 2005


Referinta online:

R21419a - VBA - save Internet file

Locul 3, noiembrie 2005


Problema

Buna ziua,

Īncerc si eu sa fac un program care sa imi salveze un fisier din Internet de exemplu sigla microsoft care stiu ca se afla la www.microsoft.com/sigla.jpg.

Am incercat sa fac o macrocomanda care sa faca acest lucru dar nu reusesc! :)

O a doua problema ar fi un form - care sa imi arate cat mai am din fisier (un fel de bara de progres cum e cea de la copy). Nu reusesc sa afisez nimic pe ecran decat cu inputbox si msgbox - in ambele cazuri mai este nevoie sa dau un click in plus pe butonul de OK.

Va multumesc.

Andrei C


Raspunsul meu

File explorer-ul Total (Windows) Commander are functia asta implementata in el. O poti accesa folosind butonul URL din toolbar. Se deschide o fereastra in care dai adresa www.microsoft.com/sigla.jpg si gata.

Daca vrei sa faci asta printr-un program, eu as face asta in C# .Net folosind clasa HttpRequest:


private static void MakeWebRequest(Uri _URI, string outfile)
{
	try
		{
			// Create the request
			HttpWebRequest _WR = (HttpWebRequest)WebRequest.CreateDefault(_URI);
			// Set the request timeout
			_WR.Timeout = 1000 * 120; // 120 seconds
			// Set the request method
			_WR.Method = "GET";
			// Set credential
			_WR.Credentials = CredentialCache.DefaultCredentials;
			// Get the response
			HttpWebResponse _WS = (HttpWebResponse)_WR.GetResponse();
			// Read the file from the response
			readFile(_WS, outfile);
		}
		catch(WebException e)
		{
			throw new Exception("WebException: " + e.Message);
		}
}

private static void readFile(WebResponse _FWS, string outfile)
{
	try
	{
		// Create the input stream.
		Stream receiveStream = _FWS.GetResponseStream();
		
		// Create a stream for output file.
		FileStream fs = new FileStream(outfile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
		
		// Create a local buffer for a temporary storage of the read data.
		byte[] buffer = new byte[1024];
		// Read the first 1024 bytes.
		int count = receiveStream.Read( buffer, 0, 1024 );
		
		// Loop to read the remaining data in blocks of 1024 bytes
		// and wrightthe data into the output file.
		while (count > 0)
		{
			fs.Write( buffer, 0, count );
			count = receiveStream.Read(buffer, 0, 1024);
		}
		
		// Close streams.
		receiveStream.Close();
		fs.Close();
		
		// Release the response object resources.
		_FWS.Close();
	}
	catch(WebException e)
	{
		throw new Exception("The WebException: "+e.Message);
	}
	catch(UriFormatException e)
	{
		throw new Exception("The UriFormatException: "+e.Message);
	}
	
}