Reputation: 100
Im trying to download a txt file at runtime in Streaming Assets folder in a Windows based game using Unity 5.6.1 and c#. I have found some data in the manual and some examples here and there and made this although its not working, I hope you can point me in the right direction. Thanks beforehand
The current test text file is called cont.txt and can be found in my site so the url is correct and tested
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class webreq : MonoBehaviour
{
void Start()
{
StartCoroutine(GetText("cont"));
}
IEnumerator GetText(string file_name)
{
string url = "http://www.mordazah.com/" + file_name + ".txt";
Debug.Log(url);
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
string savePath = string.Format("{0}/{1}.txt", Application.streamingAssetsPath, file_name);
System.IO.File.WriteAllText(savePath, www.downloadHandler.text);
}
}
}
Upvotes: 0
Views: 3615
Reputation: 18909
You are probably getting errors because the directory and path do not exist. File.WriteAllText
will create the file, or overwrite if exists, but will not create your directory.
You need to use Directory.CreateDirectory(String);
Creates all directories and subdirectories in the specified path unless they already exist.
Also use SendWebRequest as Send
is depcrecated.
See the comments inline below:
void Start () {
StartCoroutine (GetRequest ("cont.txt"));
}
IEnumerator GetRequest (string file_name) {
// use concat with joining strings
var uri = string.Concat ("http://www.mordazah.com/", file_name);
using (var webRequest = UnityWebRequest.Get (uri)) {
yield return webRequest.SendWebRequest (); // send is deprecated
if (webRequest.isNetworkError) {
Debug.LogError (webRequest.error);
}
else {
// ensure you have this directory - will not throw if it exists
Directory.CreateDirectory (Application.streamingAssetsPath);
// create the appropriate path to save to using Path.Combine()
var savePath = Path.Combine (Application.streamingAssetsPath, file_name);
File.WriteAllText (savePath, webRequest.downloadHandler.text);
}
}
}
Upvotes: 1