Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable in C# path

Tags:

c#

I need to save an .xml file in a specific location on a computer. But location could be changed based on selection of the user.

I can get user selection (from combobox) to the variable like this:

location = (string)comboBox1.SelectedItem;

But I can’t use following command to store my file because of “%location%” part. It says “Could not find a part of the path”

docSave.Save(@"C:\...\...\%location%\...\Information.xml");

Can anyone help me regarding that….?

Thank you.

like image 446
Chathuranga Bandara Avatar asked Feb 21 '26 19:02

Chathuranga Bandara


2 Answers

String.Format is what you are looking for.

string.Format("C:\\...{0}\\Information.xml", location);
like image 65
Hossein Narimani Rad Avatar answered Feb 27 '26 08:02

Hossein Narimani Rad


You should always use the Path class when you're working with paths, so if you want to get a working path from multiple parts, use Path.Combine:

string location = (string)comboBox1.SelectedItem;
string dir = "C:\dir1\dir2\%location%\dir4".Replace("%location%", location);
string filename = "Information.xml";
string fullPath = Path.Combine(dir, filename);
like image 31
Tim Schmelter Avatar answered Feb 27 '26 09:02

Tim Schmelter