Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
6 set of files come in my directory and I want to change their name :

File names are like below :

for company X:-

HD_654,
DT_654,
TD_654
For company Y :-

HD_231,
DT_231,
TD_231
Those numbers 654, 231 are different and can be different for different days . So I was not be able to hardcode. But one thing always for company X the numbers are same like 654 for all and for company Y numbers are same like here 231 for all.

So I want to change the digits for company X as HD_MMDDYYYY,DT_MMDDYYYY and TD_MMDDYYYY and for company Y as HD_YYYYDDMM, DT_YYYYDDMM, TD_YYYYDDMM
Posted
Updated 10-Jan-14 7:31am
v3
Comments
Kees van Spelde 10-Jan-14 12:55pm    
What were you not able to hard-code and in which program language do you want to solve your problem? You are not clear in that in your question. I assume that you want to rename for example the HD_654 file to HD01102014 when we take today's date.
DEbopm 10-Jan-14 13:00pm    
If I get the files for company X : HD_655, DT_655,TD_655 and for Y : HD_233,DT_233,TD_233 then tomorrow I might receive like this : for X : HD_765,DT_765,TD_765 and for Y : HD_125,DT_125, TD_125.

So for everyday basis I want to put the date extension for the files as for X HD_01102014 same for DT and TD and for Y : HD_20141001 and same for DT and TD. Is it more clear ? I want to use console C Sharp for this .
Kees van Spelde 10-Jan-14 13:11pm    
I never heard of console C sharp. Are you writing a console application in C#? Still a little bit unclear what you are doing
DEbopm 10-Jan-14 13:18pm    
yes. console application in c sharp.

Look i have two companys . one company x and other is company Y. company X sends 3 files (HD,DT and TD) and company Y also do the same (three files with same name ). Only difference is the digis for company X is different than company Y. Say if company X will send HD as HD_431 and DT_431,TD_431 , so all the files from X will be having same digis 431. and for company Y will be same digis but different from company X. I want to write a console app that will convert the digits to date format. That is for company X the names would be like HD_201401110, DT_20140110, TD_20140110. AND for Y it would be HD_10012014 like this . Is it clear now. ?
Kees van Spelde 10-Jan-14 13:17pm    
With a very simple batch file you can do something like this.

::The way the next line is used depends on the date format that is used
ren *_* *_%date:~6,2%%date:~3,2%%date:~9,4%

My thought would be to create a file in the target folder that defines the mapping between the Company Code in the HD_nnnn.txt file and the required date formatting:
00098,MMDDYYYY
50,YYYYDDMM

That way adding more Company Codes doesn't require modifying the program code...

This compares the Company Code from the HD_nnnn.txt files as strings (i.e., 050 is not the same as 50) and assumes no extraneous characters around that piece of data (and having a tab or comma to delimit it from any following text).

So here's an almost complete solution. (more error handling required...)
C#
using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApplication23
{
  class Program
  {
    const string FormatMapFilename = "FormatMap.txt";
    static Dictionary<string, string> CompanyFormatMap = new Dictionary<string, string>();
    static string WorkingPath = @"D:\Temp\";  // or get from the command line...
    static void Main(string[] args)
    {
      if (!LoadFormatMap())
        return;   // We can't proceed without it
      foreach (string hdFilename in Directory.GetFiles(Path.Combine(WorkingPath, "HD_*.txt")))
      {
        ProcessFileGroup(hdFilename);
      }
    }

    static bool LoadFormatMap()
    {
      foreach (var line in File.ReadLines(Path.Combine(WorkingPath, FormatMapFilename)))
      {
        string[] mapping = line.Split('\t', ',');
        if (mapping.Length >= 2)
        {
          CompanyFormatMap.Add(mapping[0], mapping[1]);
        }
        else
        {
          Console.Error.WriteLine("Invalid line in: " + FormatMapFilename);
          return false;
        }
      }
      return true;
    }

    static void ProcessFileGroup(string hdFilename)
    {
      string folder = Path.GetDirectoryName(hdFilename);
      string extension = Path.GetExtension(hdFilename);
      string fileDigits = Path.GetFileNameWithoutExtension(hdFilename).Split('_')[1];
      string dateFormat = null;
      using (var hdFile = new StreamReader(hdFilename))
      {
        string[] splitLine = hdFile.ReadLine().Split('\t', ',');
        if (!CompanyFormatMap.TryGetValue(splitLine[0], out dateFormat))
        {
          Console.Error.WriteLine("Unrecognized company code in: " + hdFilename);
          return;
        }
      }

      string filedate = DateTime.Today.ToString(dateFormat);
      int digitsCount = fileDigits.Length;
      foreach (string filePath in Directory.GetFiles(Path.Combine(folder, "*_", fileDigits, extension)))
      {
        string filename = Path.GetFileNameWithoutExtension(filePath);
        filename = filename.Substring(0, filename.Length - digitsCount) + filedate;
        File.Move(filePath, Path.Combine(folder, filename, extension));
      }
    }
  }
}
 
Share this answer
 
You might do something like this (not compiled, though):
C#
string GetSuffix(string filePath)
{
    var match = Regex.Match(filePath, @"_(\d{1,7})$"); // only take numbers with less digits than the choosen date format
    if (match.Success) return match.Groups[1].Value;
    return null;
}
void ReplaceSuffix(string dirPath, string oldSuffix, string newSuffix)
{
    if (string.IsNullOrEmpty(oldSuffix)) return;
    string pattern = "^(.*)"+Regex.Escape(oldSuffix)+"$";
    newSuffix = newSuffix ?? string.Empty;
    var query = from f in Directory.GetFiles(dirPath)
                let m = Regex.Match(f, pattern)                  // filter by suffix
                where m.Success
                select Path.Combine(dirPath, m.Groups[1].Value); // get the full file path minus the suffix
                
    foreach(var prefix in query) File.Move(prefix+oldSuffix, prefix+newSuffix);
}
void RenameCustomerFiles(string oneFullFilePath, string newSuffix)
{
    ReplaceSuffix(Path.GetDirectoryName(oneFullFilePath), GetSuffix(oneFullFilePath), newSuffix);
}
...
string oneFileOfCustomerX    = ...;
string newSuffixForCustomerX = ...;
RenameCustomerFiles(oneFileOfCustomerX, newSuffixForCustomerX);

string oneFileOfCustomerY    = ...;
string newSuffixForCustomerY = ...;
RenameCustomerFiles(oneFileOfCustomerY, newSuffixForCustomerY);


Cheers
Andi
 
Share this answer
 
Assuming you know the company numbers in advance (or you can't allocate them different date formats)
it's not too bad:
C#
string[] files = Directory.GetFiles(@"D:\Temp");
DateTime now = DateTime.Now;
string prefixYear = now.ToString("yyyyddMM");
string postfixYear = now.ToString("MMddyyyy");
string XCode = "654";
string YCode = "231";
foreach (string file in files)
    {
    string[] parts = Path.GetFileNameWithoutExtension(file).Split('_');
    if (parts.Length == 2)
        {
        string folder = Path.GetDirectoryName(file);
        string ext = Path.GetExtension(file);
        if (parts[1] == XCode)
            {
            File.Move(file, string.Format("{0}\\{1}_{2}{3}", folder, parts[0], postfixYear, ext));
            }
        if (parts[1] == YCode)
            {
            File.Move(file, string.Format("{0}\\{1}_{2}{3}", folder, parts[0], prefixYear, ext));
            }
        }
    }
 
Share this answer
 
Comments
DEbopm 10-Jan-14 14:10pm    
string XCode = "654";
string YCode = "231"; could not be there as this will be unknown for me and I dont know that tomorrow what digits will come . So It will never be hardcoded.
Matt T Heffron 10-Jan-14 14:27pm    
You must have some way to differentiate which files are from which company and what date format you want them to use.
Are they in different folders?
Is there data in the files to indicate?
Is there an algorithm used to generate the 3-digit codes for the companies that you can use to help?
Etc...
DEbopm 10-Jan-14 14:32pm    
hd_digit.txt for x the 1st column holds the value as 00098 nd for y hd_digit holds 50 for the 1st column in tge text file
OriginalGriff 10-Jan-14 14:30pm    
Those were examples - I would expect that you would be using text boxes or similar to enter them.
I had to put something in to make it clear what XCode and YCode were supposed to represent!
DEbopm 10-Jan-14 14:34pm    
is there any way to select files at run time ????
In C# you can do it like this

C#
DirectoryInfo d = new DirectoryInfo("The location of the folder with the files");
FileInfo[] infos = d.GetFiles();
foreach(FileInfo f in infos)
{
    var parts = f.FullName.Split('_');
    File.Move(f.FullName, parts[0] + "_" + DateTime.Now.ToString("MMddyyyy"));
}


And you probably can figure out hot to do it for company Y
 
Share this answer
 
Comments
DEbopm 10-Jan-14 14:03pm    
Kindly tell me if the file name will be like LS_PRHD_date then how to change the code ?
OriginalGriff 10-Jan-14 14:15pm    
You do need to be careful with that - if the path contains a '_' it will mess up, it loses the file extensions, and it will probably fail in production because it moves the files into the application folder from where ever they were. Since this would normally be under "Program Files" which is not normally writable you are likely to get an exception.

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