Click here to Skip to main content
15,893,790 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two files LS_PRSAHD_61417920_Cleaned.txt and LS_PRSAHD_67543245_Cleaned.txt. I want to rename the files as LS_PRSAHD_61417920.txt and LS_PRSAHD_67543245.txt.

I have tried this one . but not working.
C#
for (int i = 0; i < FilesHD.Length; i++)
            {

                FileInfo fi = new FileInfo(FilesHD[i]);
                sourcefilename = fi.Name;
                string cleanedfiles = Sourcefolder + sourcefilename;
                string originalfiles = sourcefilename.Substring(0, sourcefilename.Length - 12) + ".txt";
                if (File.Exists(cleanedfiles))
                {

                    File.Move(cleanedfiles, originalfiles);
                }

            }

Kindly give some info.
Posted
Updated 21-Jan-14 10:58am
v2
Comments
Maciej Los 21-Jan-14 16:57pm    
Not working is not informative at all. Please, be more specific. What kind of error do you have?
Philippe Mori 21-Jan-14 20:05pm    
If the text to remove is always _Cleaned, you might want to search the last occurrence of that sting in the file name and then remove it. This might allows stronger validation.

1 solution

assuming that you dont have any exception in line
C#
sourcefilename = fi.Name;

your file existence check returns false (possibly) here:
C#
if (File.Exists(cleanedfiles))

because of improper file path creation in line
C#
string cleanedfiles = Sourcefolder + sourcefilename;


use Path.Combine method to get a proper full path.
C#
cleanedfiles= Path.Combine(Sourcefolder, sourcefilename);


and to be sure, you can add 'else' part for the if(File.Exists)
 
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