简体   繁体   English

覆盖现有文件

[英]Overwrite exisiting file

I'm using JSON to download a file from the net. 我正在使用JSON从网上下载文件。 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);
}

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
}

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. 这样,当您覆盖文件时就不会丢失任何内容,并且可以在需要时轻松替换数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM