1

有人可以告诉我使用 libcurlnet 下载给定 url 的文件的正确方法吗

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);
4

1 回答 1

0

您不需要为WriteFunction声明自己的回调,委托在Easy. 您需要将委托传递给 WriteFunction 选项,而不是 WriteData 选项。后者用于您要传递给 WriteFunction 委托的对象。修复所有这些问题将为我提供以下工作代码:

void Main()
{

    Curl.GlobalInit(3);
    var downloadFileUrl ="http://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
于 2017-08-13T20:17:33.313 回答