Search code examples
c#unity-game-enginedownloadwebclientpastebin

c# webClient.DownloadFile doesn't download, it just creates an empty text file


I wanted to download a text from Pastebin(raw) into a texfile. I created an IEnumerator, but somehow it just creates an empty text file.

public IEnumerator DownloadTextFile()
{
    WebClient version = new WebClient();
    yield return version;
    version.DownloadFileAsync(new Uri(myLink), "version.txt");
}

public IEnumerator DownloadTextFile()
{
    WebClient version = new WebClient();
    yield return version;
    version.DownloadFile(myLink , "version.txt");
}

Thanks in advance.


Solution

  • WebClient is not designed to be used from within Unity3D like that, yield return version; does not wait for the file to be downloaded.

    What you could do is use the WWW class and perform the download that way. WWW is part of Unity and is designed to work in ways with the way Unity works.

    public IEnumerator DownloadTextFile()
    {
       WWW version = new WWW(myLink);
       yield return version;
       File.WriteAllBytes("version.txt", version.bytes);
    
       //Or if you just wanted the text in your game instead of a file
       someTextObject.text = version.text;
    }
    

    Be sure to start the DownloadTextFile by calling StartCoroutine(DownloadTextFile())