c#webClient.DownloadFile没有下载,只是创建一个空文本文件

时间:2017-08-31 20:23:49

标签: c# unity3d download webclient pastebin

我想将 Pastebin(raw)中的文本下载到texfile中。 我创建了一个IEnumerator,但不知何故它只是创建一个空文本文件。

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");
}

提前致谢。

3 个答案:

答案 0 :(得分:4)

WebClient并非设计为在Unity3D中使用,yield return version;不等待文件下载。

您可以使用WWW类并以此方式执行下载。 WWW是Unity的一部分,旨在以Unity的工作方式工作。

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;
}

请务必致电StartCoroutine(DownloadTextFile())

启动DownloadTextFile

答案 1 :(得分:3)

自从WWW API处理线程问题以来,Scott Chamberlain的solution正确的以及推荐的方式在Unity中执行此操作在后台。您只需使用协同程序下载它,然后使用Scott提到的File.WriteAllXXX函数之一手动保存它。

我正在添加此答案,因为问题是专门询问WebClient,有时候使用WebClient很好,例如大数据。

问题在于你正在屈服于WebClient。你不必像你一样在协程中产生WebClient。只需订阅将在另一个Thread上调用的DownloadFileCompleted事件。为了在DownloadFileCompleted回调函数中使用Unity函数,您必须使用this帖子中的UnityThread脚本,并在UnityThread.executeInUpdate函数的帮助下执行Unity函数。

这是一个完整的示例(需要UnityThread):

public Text text;
int fileID = 0;

void Awake()
{
    UnityThread.initUnityThread();
}

void Start()
{
    string url = "http://www.sample-videos.com/text/Sample-text-file-10kb.txt";
    string savePath = Path.Combine(Application.dataPath, "file.txt");

    downloadFile(url, savePath);
}

void downloadFile(string fileUrl, string savePath)
{
    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DoSomethingOnFinish);
    webClient.QueryString.Add("fileName", fileID.ToString());
    Uri uri = new Uri(fileUrl);
    webClient.DownloadFileAsync(uri, savePath);
    fileID++;
}

//THIS FUNCTION IS CALLED IN ANOTHER THREAD BY WebClient when download is complete
void DoSomethingOnFinish(object sender, AsyncCompletedEventArgs e)
{
    string myFileNameID = ((System.Net.WebClient)(sender)).QueryString["fileName"];
    Debug.Log("Done downloading file: " + myFileNameID);

    //Ssafety use Unity's API in another Thread with the help of UnityThread
    UnityThread.executeInUpdate(() =>
    {
        text.text = "Done downloading file: " + myFileNameID;
    });
}

答案 2 :(得分:1)

确保将WebClient放在using语句中,以便正确处理并确保下载完成。对于Async版本,您需要确保在忙碌时不要保释。

        //Method 1
        using (var version = new WebClient())
            version.DownloadFile("https://pastebin.com/raw/c1GrSCKR", @"c:\temp\version.txt");

        // Method 2 (better if you are working within Task based async system)
        //using (var version = new WebClient())
        //    await version.DownloadFileTaskAsync("https://pastebin.com/raw/c1GrSCKR", @"c:\temp\version.txt");

        // Method 3 - you can't dispose till is completed / you can also register to get notified when download is done.
        using (var version = new WebClient())
        {
            //version.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
            //{

            //};
            version.DownloadFileAsync(new Uri("https://pastebin.com/raw/c1GrSCKR"), @"c:\temp\version.txt");

            while (version.IsBusy) {  }
        }