I can't seem to figure this out. Please help.

I have a folder with mulitple files whose file-names are in the following format:

Code Snippet



What I would like to do is the following:

1. See if a filename.xml.bak* file exsists

2. If it does, find the last one, increment by 1, and put the resulting string into a string variable.

I think I have the logic right, but I'm new to programming and can't seem to find the right syntax/methods to accomplish it. Thanks in advance.

Re: Visual C# General File Name Problem


Code Snippet

if (System.IO.Directory.Exists("c:\\NewFolder"))


System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("c:\\NewFolder");

System.IO.FileInfo[] files;

files = di.GetFiles();

string filename = "c:\\NewFolder\\filename.xml.bak";

for (int I = 1; I <= files.Length - 1; I++)


if (I == files.Length - 1)


if (System.IO.File.Exists(filename + I))


System.IO.FileStream fs = new System.IO.FileStream(filename + I.ToString(), System.IO.FileMode.Open);

System.IO.StreamReader sr = new System.IO.StreamReader(fs);

string filedata = sr.ReadToEnd();







Re: Visual C# General File Name Problem

Suprotim Agarwal

Dear computerjunkie,

There is a similar example given over here. I would recommend studying it and using it in your code.


Suprotim Agarwal

Re: Visual C# General File Name Problem


If you are really trying to find the last one (the one with the highest value at the end) and not stop when a gap is found... here's my attempt:

Code Snippet

const string DIRECTORY_TO_SEARCH = "C:\\MyTest";

const string FILES_TO_FIND = "filename.xml.bak";

string[] szFiles;

string szTemp;

Int32 nNew = 0;

Int32 nCurrent;

Int32 nStartAt = FILES_TO_FIND.Length;

// Get files that match search pattern.

szFiles = System.IO.Directory.GetFiles(DIRECTORY_TO_SEARCH, FILES_TO_FIND + "*");

foreach( string szFile in szFiles )


// Strip off just the filename.

szTemp = System.IO.Path.GetFileName(szFile);

// Get the right-most portion of the file name (after the

// known part of the file name).

szTemp = szTemp.Substring(nStartAt, szTemp.Length - nStartAt);

// Use TryParse to make sure it parses to a number,

// otherwise the current file is ignored because it

// doesn't conform to the file naming pattern expected.

if( Int32.TryParse(szTemp, out nCurrent) )


// If the current value exceeds the highest

// known value so far, reset the highest

// known value.

if( nCurrent > nNew )

nNew = nCurrent;



// Increment by one to get newest suffix for

// filename.