Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Path= @"G:\Trial\WorkDirectory\Kabhi Kabhi Aditi\abc.npr"; want to replace abc.npr with xyz.xml
Posted
Comments
BillW33 3-Sep-12 10:27am    
If one of the solutions given answers your question you should mark it as the answer so that this question gets removed from the list of unanswered questions.

Go for the methods in System.IO.Path[^]:
C#
string originalPath = @"G:\Trial\WorkDirectory\Kabhi Kabhi Aditi\abc.npr";
string newFileName = "xyz.xml";

string newPath = System.IO.Path.Combine(
    System.IO.Path.GetDirectoryName(originalPath),
    newFileName
);
 
Share this answer
 
v2
Comments
lewax00 31-Aug-12 12:07pm    
Exactly, no need to reinvent the wheel, +5
lukeer 3-Sep-12 1:38am    
Thanks.
BillW33 31-Aug-12 16:19pm    
Short & sweet, +5
lukeer 3-Sep-12 1:38am    
Thank you.
C#
string originalPath = @"G:\Trial\WorkDirectory\Kabhi Kabhi Aditi\abc.npr";
originalPath = originalPath.Replace(Path.GetFileName(originalPath), "xyz.xml");
 
Share this answer
 
Comments
lewax00 31-Aug-12 12:09pm    
This will cause problems if the path ever contains the filename somewhere else ("." is valid in directory names, so a path like "G:\Trial\WorkDirectory\abc.npr\Kabhi Kabhi Aditi\abc.npr" is possible).
Kuthuparakkal 3-Sep-12 8:25am    
Agreed...
Hello,

Check below code it will used replace file name with new file name


C#
string ReplaceText = @"G:\Trial\WorkDirectory\Kabhi Kabhi Aditi\abc.npr";
            ReplaceText = ReplaceText.Replace(ReplaceText.Substring(ReplaceText.LastIndexOf(@"\") + 1, ReplaceText.Length - (ReplaceText.LastIndexOf(@"\") + 1)), "xyz.xml");



Thanks
Gaurav Dhol
 
Share this answer
 
Comments
lewax00 31-Aug-12 12:06pm    
Technically correct (at least it appears to be, I haven't tested it), but it's very unclear and much more complicated than it needs to be.
C#
string path= @"G:\Trial\WorkDirectory\Kabhi Kabhi Aditi\abc.npr";
int index = path.LastIndexOf("\");
path = path.SubString(0,index);
path +="\zyz.xml" ;


Just another solution :)

Regards.
 
Share this answer
 
v2
Comments
Christian Amado 31-Aug-12 13:31pm    
Why downvoted?
Use this:
C#
string path = @"G:\Trial\WorkDirectory\Kabhi Kabhi Aditi\abc.npr"
string filename = Path.GetFileName(path);


Refer Path.GetFileName Method[^].



--Amit
 
Share this answer
 
Comments
lukeer 31-Aug-12 6:41am    
But the filename is exactly that part, that the OP is not interested in.

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