0

I am trying to increment the filename (e.g., "file1.csv", "file2.csv", etc.), each time a new file is generated. I followed this thread Increment the file name if the file already exists in c# but the solution is not useful for my case. What I want to do is check if the file exists in the first place and if it does write in it. If it doesn't create one and write. The problem is that if the file exists but it's from another user, I want the system to increment the file number and not write to the same file just because it exists. What I have so far:

public void saveFile()
{
    int count = 0;
    string title = "TimeStamp,Name,Trial,Time_spent-dist,Time_spent_tar\n";
    string output = System.DateTime.Now.ToString("mm_ss_ffff") + "," +
                      currentScene.name.ToString() + "," +
                      trialNum.ToString() + "," +
                      timerDistractor.ToString() + "," +
                      timerTarget.ToString();
    string fname = "User_" + count + ".csv";
    string path = Path.Combine(Application.persistentDataPath, fname);
    if (File.Exists(path))
    {
        File.AppendAllText(path, "\n" + output);
    }
    else
    {
        StreamWriter writer = new StreamWriter(path);
        writer.WriteLine(title + "\n" + output);
        writer.Close();
    }
}

Any pointers?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Phoenix
  • 73
  • 6
  • 2
    How will know the difference between a file that exists from another user? Maybe you should accept a user_ID as an argument to the function and include it as part of the name. Then there would never be a conflict. – Joel Coehoorn May 27 '22 at 14:08
  • If the first user generates a file "User_0.csv", then the second user cannot have the same file name so the count variable should add 1 and get "User_1.csv".And so on and so forth for the next users. To be honest, having a UI input at the beginning of the app and get the user id from there would be a lot easier. – Phoenix May 27 '22 at 14:17
  • 2
    How do you expect to know if User_0.csv belongs to the current who wants to append, or a different user? – Joel Coehoorn May 27 '22 at 14:20
  • Verify `Environment.UserName` or https://stackoverflow.com/questions/1240373/how-do-i-get-the-current-username-in-net-using-c against: https://stackoverflow.com/questions/7445182/find-out-file-owner-creator-in-c-sharp | https://stackoverflow.com/questions/153087/getting-setting-file-owner-in-c-sharp – Rand Random May 27 '22 at 14:35
  • 1
    FYI - File.AppendAllText will create the file if it doesnt exist your if block is not necessary – Rand Random May 27 '22 at 14:37

0 Answers0