winforms 保存自动递增的文本文件file_01.txt、file_02.txt、file_03.txt C#

az31mfrm  于 2022-11-16  发布在  C#
关注(0)|答案(1)|浏览(170)

所以我用winforms做了一个程序,当我保存我的文本文件时,我想让它自动递增。
我好像不能让它工作...
这是我的代码

private void Button1_Click(object sender,EventArgs e)
    {
        using (SaveFileDialog saveFileDialog = new SaveFileDialog())
        { 
            string filePath = "C\\";
            int fileCount = 0;
            String fileName = "File_0" + $"{fileCount}";
            bool checkFileName = true;
            while (checkFileName)
            {
                fileName = "File_0" + $"{fileCount}.txt";
                fileCount++;

                string checkName = filePath + "\\" + fileName;
                checkFileName = File.Exists(checkName);
            }

            saveFileDialog.FileName = fileName;
            saveFileDialog.Title = "Save Files";
            saveFileDialog.InitialDirectory = $"{filePath}";
            saveFileDialog.CheckPathExists = true;
            saveFileDialog.DefaultExt = "txt";
            saveFileDialog.Filter = "Text files |*.txt";
            saveFileDialog.RestoreDirectory = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter sw = new StreamWriter(saveFileDialog.OpenFile()))
                {
                    foreach (string item in regoListBox.Items)
                    {
                        sw.WriteLine(item);

                    }
                }
            }
        }
    }
nwlls2ji

nwlls2ji1#

它不工作的原因是您没有正确指定filePath。因此它无法检查增量文件名。
将其更改为:

//string filePath = "C\\";
string filePath = "C:\\";

相关问题