1

Can someone show me the correct way to download a file given a url using libcurlnet

FileStream fs = new FileStream("something.mp3", FileMode.Create);
WriteData wd = OnWriteData; 
easy.SetOpt(CURLoption.CURLOPT_URL, downloadFileUrl); 
easy.SetOpt(CURLoption.CURLOPT_WRITEDATA, wd);

if ("CURLE_OK" == easy.Perform().ToString())
{
    //save_file 
}


 static System.Int32 OnWriteData(FileStream stream, byte[] buf, Int32 size, Int32 nmemb, Object extraData)
{
    stream.Write(buf, 0, buf.Length);
    return size * nmemb;
} //OnWriteData


public delegate System.Int32
   WriteData(
      FileStream stream, //added parameter
      byte[] buf, Int32 size, Int32 nmemb, Object extraData);
Eminem
  • 7,206
  • 15
  • 53
  • 95

1 Answers1

0

You don't need to declare your own callback for the WriteFunction, the delegate is declared in Easy. And you need to pass the delegate to the WriteFunction option, not to the WriteData option. The latter is for the object you want to pass to the WriteFunction delegate. Fixing all those things will give the following working code for me:

void Main()
{

    Curl.GlobalInit(3);
    var downloadFileUrl ="https://i.stack.imgur.com/LkiIZ.png"; 

    using(var easy = new Easy())
    using(FileStream fs = new FileStream(@"something2.png", FileMode.Create))
    {   
        // the delegate points to our method with the same signature
        Easy.WriteFunction wd = OnWriteData; 
        easy.SetOpt(CURLoption.CURLOPT_URL, downloadFileUrl); 
        // we do a GET
        easy.SetOpt(CURLoption.CURLOPT_HTTPGET, 1); 
        // set our delegate
        easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wd);
        // which object we want in extraData
        easy.SetOpt(CURLoption.CURLOPT_WRITEDATA, fs);

        // let's go (notice that this are enums that get returned)
        if (easy.Perform() == CURLcode.CURLE_OK)
        {
          // we can be sure the file is written correctly
          "Success".Dump();
        }
        else 
        {
          "Error".Dump();
        }
    }
}

System.Int32 OnWriteData(byte[] buf, Int32 size, Int32 nmemb, Object extraData)
{
    // cast  extraData to the filestream
    var fs = (FileStream) extraData;
    fs.Write(buf, 0, buf.Length);
    return size * nmemb;
} //OnWriteData
rene
  • 41,474
  • 78
  • 114
  • 152