Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having some trouble with my program. Is there anyway to check if a file exists but when every file have a different name. For Example: 1.txt 2.txt 3.txt 4.txt. At the moment, my code creates separate files but when the app is closed and re-opened it re-writes the txt files. I am using Visual Studio 2019 and Coding in C#. This is some of the code I am using:

    int Count = 1;
    string path = "D:\Bot\Bot\Tasks\{0}.txt";
    private void btn1_Click(object sender, EventArgs e)
    {
        if (System.IO.File.Exists(path))
        {
            Count++;
        }
        string selectedsite = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
        string selectedsize = this.comboBox1.GetItemText(this.comboBox2.SelectedItem);
        string selectedproduct = this.comboBox1.GetItemText(this.comboBox3.SelectedItem);
        string selectedproxies = this.comboBox1.GetItemText(this.comboBox4.SelectedItem);
        string selectedprofiles = this.comboBox1.GetItemText(this.comboBox5.SelectedItem);
        string[] FileInfo = { selectedsite, " ", selectedsize, " ", selectedproduct, " ", selectedproxies, " ", selectedprofiles };
        var newFileName = string.Format(@"D:BotBotTasks{0}.txt", Count);
        Count++;
        System.IO.File.WriteAllLines(newFileName, FileInfo);


    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

you could try change the "if" at the beginning to a "while" until you get a "count" which corresponds to a non-existing file.

If I understand your problem correctly, below is the solution I thought of and tested it in an example project:

while(System.IO.File.Exists(string.Format(@"D:BotBotTasks{0}.txt", Count)))
{
  Count++;  
}

edit:
I changed it back to my original suggestion which is a valid statement after all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...