我如何使这段代码创建多个.txt文件,而不仅仅是一个



所以,正如代码工作得很好,但是它只创建一个txt文件,我希望它每次运行时都创建一个新文件,理想情况下,在Unity中创建一个文件夹来存储所有这些文件,而不仅仅是在资产文件夹中。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Unity.UI;
public class Hippocampus : MonoBehaviour
{
QuoteText qT;
void OnEnable () 
{
qT = FindObjectOfType<QuoteText>();
}

public void CreateText()
{
string path = Application.dataPath + "/Job" + 01 + ".txt"; // file path and name of the file         TODO: growing list, also create a new folder or directory like:     @"E:ProjectC_SharpTutorialConsole_AppFileSystemOutput"; for example
if (!File.Exists(path))
{
File.WriteAllText(path, + qT.area + "m² nn");
}

string content = "$" + qT.sqreMeterRate * qT.area + "n" + 
qT.tileMod + "n" +
qT.ironMod + "n" +
qT.roofFall + "n" +
qT.snowMod + "n" +
qT.skyLightMod + "n" +
qT.hotWaterMod + "n" +
qT.boxGutterMod + "n" +
qT.ceilingMod + "n" +
qT.overSizedMod + "n" +
qT.floorLevel + "n" +
qT.rakingMod + "n" +
qT.solidRaftersMod + "n" +
qT.aCMod + "n" +
qT.ductingMod + "n" +
qT.commercialMod+ "n"; 
File.AppendAllText(path, content);
}
}

Thanks for the help

这样做的一种方法是每次运行该方法时将索引增加1。这样就可以了:

const int NUM_DIGITS = 2        
string dirPath = Application.dataPath;
var files = Directory.GetFiles(dirPath, "Job*");
int nextFileNo = (int)(files.Length == 0 ? 0 : 
files.Max(x => decimal
.Parse(Path.GetFileName(x)
.Substring(3, NUM_DIGITS)))) + 1;
string path = $"{dirPath}\Job{nextFileNo.ToString($"D{NUM_DIGITS}"}.txt";

如果您计划有超过99个文件,请将NUM_DIGITS更改为更高的数字。

最新更新