如何检查文件是否存在于 C# 中? [英] How do I check if a file exists in C#?

查看:31
本文介绍了如何检查文件是否存在于 C# 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序有问题.无论如何要检查文件是否存在,但是当每个文件都有不同的名称时.例如:1.txt2.txt3.txt4.txt.目前,我的代码创建了单独的文件,但是当应用程序关闭并重新打开时,它会重新写入 txt 文件.我正在使用 Visual Studio 2019 和 C# 中的编码.这是我正在使用的一些代码:

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:\Bot\Bot\Tasks\{0}.txt", Count);
        Count++;
        System.IO.File.WriteAllLines(newFileName, FileInfo);


    }

推荐答案

你可以在一个循环中查询每个文件是否存在,或者你可以列出目录中的所有文件,找到最大的然后从那里开始

You could query every file existence in a loop, or you can list all the files in the directory, find the max one and go from there

Count = Directory.GetFiles(@"D:\Bot\Bot\Tasks")
  .Select(Path.GetFileNameWithoutExtension)
  .Select(f => int.TryParse((f), out var x) ? x : int.MinValue)
  .Max() + 1;

这篇关于如何检查文件是否存在于 C# 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆