c# - 将文件写入名称递增的路径

标签 c# file unity3d

Unity3D 脚本中,我有以下简单地将文件(图像)写入路径:

var path = Application.persistentDataPath + "/ocr.jpg";
FileOperations.Create(blah, path);

当然在别处的static实用程序中,我已经实现了这个辅助函数如下:

public static void Create(byte[] bytes, string path)
{
    var file = File.Open(path, FileMode.Create);

    using ( var binary = new BinaryWriter(file) )
    {
        binary.Write(bytes);
        file.Close();
    }
}

我意识到我的实现只会创建一个文件;即覆盖同名的现有文件 (ocr.jpg) 所以我写了以下代码:

public static void Create(byte[] bytes, string path)
{
    if ( !File.Exists(path) )
    {
        var file = File.Open(path, FileMode.Create);

        using ( var binary = new BinaryWriter(file) )
        {
            binary.Write(bytes);
            file.Close();
        }
    }
    else
    {                                                       
        int counter = 1;
        path = Application.persistentDataPath + "/ocr" + "_" + counter + ".jpg";

        var file = File.Open(path, FileMode.Create);

        using ( var binary = new BinaryWriter(file) )
        {
            binary.Write(bytes);
            file.Close();
        }
    }
}

然后,我意识到每次运行该应用程序时,计数器 都会设置回 1,所以现在我的 ocr_1.jpg 是写多了!

(不要介意这个半解决方案已经很难看,因为它引入了一些特定于 Unity 的东西。我希望不要在我的辅助实用程序类中包含 using UnityEngine。)

接下来我试着递归的做了,如下:

public static void Create(byte[] bytes, string path)
{
    if ( !File.Exists(path) )
    {
        var file = File.Open(path, FileMode.Create);

        using ( var binary = new BinaryWriter(file) )
        {
            binary.Write(bytes);
            file.Close();
        }
    }
    else
    {                                                       
        int counter = 1;
        path = Application.persistentDataPath + "/ocr" + "_" + counter + ".jpg";

        Create(bytes, path);
    }
}

但是我收到了 StackOverFlow 错误消息。我不明白为什么,因为检查应该一直持续到没有同名文件为止,等等...

有人能帮我理解我做错了什么,以及我如何才能实现我的目标,即根据需要多次运行应用程序并按顺序创建图像:ocr.jpg, ocr_1.jpg, ocr_2.jpg, ocr_3.jpg, 等...

此外,如果我发现如何以我的实用程序类不必包含与统一相关的内容的方式执行此操作,那就太好了;即只有 using System.IO

最佳答案

如果你传入一个已经存在的路径

path = Application.persistentDataPath + "/ocr" + "_" + counter + ".jpg";

也存在,你继续调用 Create 方法而不增加计数器,因此堆栈溢出。考虑将计数器值传递给递归创建方法,并在每次迭代中更新它,直到它遇到一个不存在的文件名。

关于c# - 将文件写入名称递增的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43996975/

相关文章:

android - 以编程方式检索 Android 中的文件大小

ruby - 无法读取名称中包含问号的文件

c# - Unity iOS 异常中的 XML 序列化

c# - 如何在unity inspector中制作折线图

c# - 处理在不同线程中读取的 TCP Socket 数据

c# - 如何自动滚动到包装面板中的特定项目?

c# - 将一种类型转换为另一种类型

c# - 在javascript中转义内联c#脚本中的双引号

file - 检查文件在不同域上是否相同

unity3d - 什么是烘焙 GI 设置中的环境光遮蔽?