Home > Software engineering >  C# Problem incrementing a file name when the file name already exists
C# Problem incrementing a file name when the file name already exists

Time:07-28

File name format = 123456.1.pdf Example: Entered 123456 in the textbox. If a file by that number exists the program would increment the number to 123456.1 Entered 123456.1 in the textbox. If a file by that number exists the program would increment the number to 123456.2 Entered 123456.11 in the textbox. If a file by that number exists the program would increment the number to 123456.12

Problem is when 123456.9 exists, the program increments it to 123456.110 or 123456.1111 What am I doing wrong? Thank you for your help.

MyWO = WO.Text; 
string plusOne = MyWO.Substring(MyWO.Length - 1);
string FnlName;
int cnt;
if (MyWO.Length == 8 ) { cnt = Convert.ToInt32(plusOne)   1; }
else { cnt = 1; }

while (File.Exists(savePath   MyWO   ".pdf"))
{
    if (MyWO.Length == 6)
    {
        FnlName = (MyWO   "."   cnt.ToString());
    }
    else
    {
        string Fnl = MyWO.Remove(MyWO.Length - 1, 1);
        FnlName = (Fnl   cnt.ToString());
    }
    cnt  ;
}

CodePudding user response:

I suggest a simple for loop: we can try i = 0, 1, 2, ... until we find fileName that's no existing:

string name = WO.Text;

string fileName = null;

for (int i = 0; ;   i) {
  fileName = $"{name}{(i == 0 ? "" : "."   i.ToString())}.pdf";

  if (!File.Exists(Path.Combine(savePath, fileName)))
    break;
}

// now fileName is a non-existing file name in "name.index.pdf" format
// Path.Combine(savePath, fileName) - complete file name

CodePudding user response:

Something like this ought to do you:

public static string GenerateFileName( string fn )
{
  Match m = rxFileNamePattern.Match(fn) ;
  if (!m.Success) throw new Exception("Invalid name") ;
  
  string pfx =            m.Groups["pfx"].Value   ;
  int    sfx = int.Parse( m.Groups["sfx"].Value ) ;
  string ext =            m.Groups["ext"].Value   ;
          
  string nextName = fn ;
  bool exists ;

  while ( (exists=File.Exists(nextName)) )
  {
    nextName = string.Format( "{0}{1}{2}", pfx, sfx, ext ) ;
  }
                                      
  return nextName;
}

const RegexOptions rxOptions = RegexOptions.IgnoreCase
                             | RegexOptions.IgnorePatternWhitespace
                             ;

private static readonly Regex rxFileNamePattern = new Regex(@"
    ^                  # start-of-text, followed by 
    (?<pfx>[0-9] [.])? # an optional prefix consisting of 1 or more digits, followed by a '.', followed by
    (?<sfx>[0-9] )     # a mandatory suffix, consisting of 1 or more digits, followed by
    (?<ext>[.]pdf)     # a '.pdf' extension, followed by
    $                  # end-of-text
  ",
  rxOptions
);  

CodePudding user response:

The issue is that you're only using strings of length 6 or 8. Once you get two digits after the decimal your string is now 9 characters and your code doesn't like that.

The answer is to not work with fixed lengths and let the code work it out.

Here's how:

int number = 0;
int version = 1;
string filename = "";
MyWO = WO.Text;
var parts = MyWO.Split('.');
if (parts.Length <= 2
    && int.TryParse(parts[0], out number)
    && (parts.Length == 1 || int.TryParse(parts[1], out version)))
{
    while (File.Exists(filename = Path.Combine(savePath, $"{number}.{version}.pdf")))
    {
        version  ;
    }
    /*
        Do something here with the `filename`
    */
}
else
{
    Console.WriteLine("Bad user input");
}
  •  Tags:  
  • c#
  • Related