So I am making a program using winforms, and when I save my text file I want it to auto increment. Example saves as file_01.txt, file_02.txt, file_03.txt
I can't seem to get it to work...
Here's my code
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);
}
}
}
}
}
CodePudding user response:
The reason it does not work is because you are not specifying filePath
correctly. Therefore it fails to check for incremental filenames.
Change it to this:
//string filePath = "C\\";
string filePath = "C:\\";