marceltje marceltje - 4 days ago 5
C# Question

make a string[] to a regular string

I'm trying make the user select a path, which the program will later on use, the reason why i want it to write it to a file, may be a little irrelevant but i see it as the simplest way for myself to handle the user wanting it to change it at anytime trough the GUI. I'm trying to what i believe is a string array converted to a normal string to use for File.Writealltext but i am failing to do so.

The code i am using is as follows.

string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath).ToString();
File.WriteAllText(@"/Data/storagedir.cfg", insertstringhere);


The entire strech of code(form load) is as follows.

private void savelocation_Load(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();

if (result == DialogResult.OK)
{
string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath).ToString();
File.WriteAllText(@"/Data/storagedir.cfg", insertstringhere);
}
else
{
MessageBox.Show("Something went wrong");
}
}


The error is as follows: CS0029 "Cannot implicitly convert type 'string' to 'string[]' "

Answer

To write all the directories names into storagedir.cfg you can use WriteAllLines:

string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath);
File.WriteAllLines(@"/Data/storagedir.cfg", selecteddir);
             ^^^^^

That takes an array as second parameter.

Or use String.Join

string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath);
File.WriteAllText(@"/Data/storagedir.cfg", String.Join(", ", selecteddir);

If you're trying to save the selected path to storagedir.cfg:

File.WriteAllText(@"/Data/storagedir.cfg", olderBrowserDialog1.SelectedPath)
Comments