Click here to Skip to main content
15,909,039 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create txt file.

If txt is created for the first time, you get number1.

If txt was previously created, you get the number + 1. The number of occurrences of +1 add up.(Number + 1 did. But 2 times I have been number 1 is always going on.)

What I have tried:

string path= @"C:\Example\Example.txt";
int number;
string foldername;
int count=0;

if(File.Exists(path))
{
   using (TextWriter tw=new StreamWriter(path))
{
    tw.Writeline();
    count++;
    number=count;
}
if(count !=0)
{
     number=number+1;
     foldername="T" +number;
}

}

else if (!File.Exists(path))
{
   File.Create(path).Dispose();
   using(TextWriter tw=new StreamWriter(path))
{
   tw.Writeline();
   count=1;
   foldername="T" + count;
}

}
Posted
Updated 12-Nov-18 10:21am

Hi,
You made your work so complicated. I wrote you the part till provides you the right index for your file name. If you needed more help then let me know I will complete the solution.
C#
int count = 0;
string fileName = "Example.txt";
string path = @"C:\Example\";
if (File.Exists(Path.Combine(path, fileName)))
    count = Directory.EnumerateFiles(path).Count();
count++;
//Here you go the count now is ready to be your file index.
fileName = Path.Combine(path, $"Example{count}.txt");


Cheers,
AH
 
Share this answer
 
You looks like you could use a do...while loop to go through successive files, right now it looks like you try only the "raw" filename and change to raw1 if the original exists.

You could incorporate this into your code to get the last numbered version of the file. The syntax may not be 100% as I am limited to notepad at the moment
C#
private int GetLastFileNumber(string FileFolder, string Filename, string FileExtension) {
  int FileCount  = 0;
  string FileCheck;
  string FileExists = True;
  do {
    if (FileCount == 0) { FileCheck = Filename + "." + FileExtension; }
    else { FileCheck = string.Format("{0}{1}.{2}", FileName, FileCount, FileExtension);
    FileExists = File.Exists(FileFolder+FileCheck)
    FileCount++
  } while(FileExists);
  return FileCount;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900