繁体   English   中英

覆盖现有文件

[英]Overwrite exisiting file

我正在使用JSON从网上下载文件。 我现在想要将文件保存到设备(我已经完成),但每次运行应用程序时,我都会再次保存文件。 即使它已经存在。

我如何修改下面的代码,以便如果已经在具有相同名称的保存位置找到了该文件的副本,则不会创建该文件的新副本?

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

检查文件是否存在。 如果没有,请创建它:

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

我倾向于检查文件是否存在,如果是,我将日期附加到文件名,您也可以轻松地跳过写入文件:

// 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. 

理想情况下,如果要保存所有文件,则文件命名模式应包含此可能性。

如果需要保留所有数据(例如数据库),您可能还需要查看存档过程。 这样,当您覆盖文件时就不会丢失任何内容,并且可以在需要时轻松替换数据。

暂无
暂无

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

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