views:

161

answers:

3

Hi,

I have a template file in a folder " c:\template_folder".

At runtime, I will create a new folder " c:\new_folder" and wish to copy the template file to the new_folder only if the file doesnt exist.

description: for the first time, I will copy the template file to the new_folder and rename it with username... so that after first time the loop finishes, i will have 8 excel files with username as the name of the each file.

for the second loop, if I have to copy the template file to new_folder and rename it to the username, if the file with the user name already exists, then it shouldnt copy the file to the folder.

I am addin the snippet of the code for reference.

foreach (FileInfo fi in templateFile)
{
    string oldfilename = null;
    string newfilename = null;
    if (dir.Exists)
    {

          fi.CopyTo(Path.Combine(dir.ToString(), fi.Name));
          FileInfo fileName = new FileInfo(fi.Name);
          oldfilename = Path.Combine(dir.ToString(), fileName.ToString());
          newfilename = Path.Combine(dir.ToString(), tempUserName + " "   + "E" + tempUserID + " VIPv7.0.xls");


          //if( !dir.ToString().Contains(newfilename))
          foreach( FileInfo fileList in fileNames)
          {
            if (fileList.Exists == false)
              File.Move(oldfilename, newfilename);
          }
    } 
}

please help me in working this.

thanks ramm

A: 

You want to use File.Exists(path) instead of the commented out line to check if the file exists

SpaceghostAli
+3  A: 

To conditionally move a file only if it doesn't already exist you would do it like this:

if (!File.Exists(newfilename)) 
{
    File.Move(oldfilename, newfilename);
}

Your code snippet confuses me, so I hope I've answered your question correctly. If I'm missing something please let me know.

Joseph
+3  A: 

Your code doesn't seem correct to me (it doesn't compile), but you can check if a file exists by calling File.Exists(filename), so:

      foreach( FileInfo fileList in fileNames)
      {
        if (!File.Exists(newfilname))
          File.Move(oldfilename, newfilename);
      }
Philippe Leybaert