N0xus
N0xus

Reputation: 2724

Overwrite exisiting file

I'm using JSON to download a file from the net. I'm now wanting to save the file to device (which I've done), but each time I run the application, I save the file again. Even though it already exists.

How can I modify my code below so it doesn't make a new copy of the file if one is already found at the save location with the same name?

IEnumerator Start ()
{
    WWW urlToLoad = new WWW(url);
    yield return urlToLoad;
    Debug.Log(urlToLoad.text);

    jsonContents = urlToLoad.text;
    var n = JSON.Parse(jsonContents);
    jsonURL = n["data"][0];
    Debug.Log(jsonURL.ToString());


    string[] splitJSONURL = jsonURL.Split('/');
    string bundle = splitJSONURL[splitJSONURL.Length - 1];
    SaveBytesAsFile(Application.persistentDataPath + "/" + bundle, urlToLoad.bytes);

}

void SaveBytesAsFile(string filePath, byte[] array)
{
    print("Saving to: " + filePath + " :: " + array.Length);

    File.WriteAllBytes(filePath, array);
}

Upvotes: 1

Views: 8653

Answers (2)

Robert H
Robert H

Reputation: 11730

I tend to check if the file exists, if so I append the date to the filename, you can easily skip writing the file as well:

// With a new filename:
if (File.Exists(filePath))
{
    File.WriteAllBytes(filepath + "-" + DateTime.Now.ToString("yyyy-MM-dd-hhmm") + ".txt", array);
}

// To skip writing the file all together, follow @PatrickHofman's answer. 

Ideally your file naming pattern should encompass this possibility if you want to save all files.

You may also want to look into an archival process if it's required that you retain all the data, such as a database. This way you lose nothing when you overwrite the file and can easily replace the data if needed.

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156978

Check if the file exists. If it doesn't, create it:

if (!File.Exists(filePath))
{
    File.WriteAllBytes(filePath, array);
}
else
{
    // do some magic, create an other file name or give an error
}

Upvotes: 2

Related Questions