-1

So, as is the code works fine, however it only create one txt file, I would like it to create a new file each time it is run and Ideally create a folder within Unity to store all these rather than just in the assets folder.

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:\Project\C_Sharp\Tutorial\Console_App\FileSystem\Output\"; for example

        if (!File.Exists(path))
        {
           File.WriteAllText(path, + qT.area + "m² \n\n");
        }
        
        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

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Ben
  • 23
  • 7

1 Answers1

0

One way of doing this is to increase the index by 1 each time you run the method. Something like this would work:

   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";

If you plan on having more than 99 files change NUM_DIGITS to a higher number.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22