Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace '\' with '/' in a String C# WinForm App

Can anyone please suggest a way to replace back-slash '\' with slash '/' in a string. Basically the string is a path. I have tried using Replace() method of string, but its not working.

Thanks

like image 633
kobra Avatar asked Mar 26 '26 03:03

kobra


1 Answers

You'll need to capture the result of the Replace (strings are immutable), and ensure you use character-escaping for the \:

string path = Directory.GetCurrentDirectory();
path = path.Replace("\\", "/");

For info; most of the inbuilt methods will accept either, and assuming you are on Windows, \ would be more common anyway. If you want a uri, then use a Uri:

string path = Directory.GetCurrentDirectory();
Uri uri = new Uri(path); // displays as "file:///C:/Users/mgravell/AppData/Local/Temporary Projects/ConsoleApplication1/bin/Debug"
string abs = uri.AbsolutePath; // "C:/Users/mgravell/AppData/Local/Temporary%20Projects/ConsoleApplication1/bin/Debug"
like image 120
Marc Gravell Avatar answered Mar 28 '26 18:03

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!