Reputation: 445
This is a beginners question but the true is I never needed to use a method like this!
So I´ll need your patience..
I have several strings named t1, t2, t3, t4...and i want to write them to a file, one at each line
so i open the file ..
string t1 = "aaa";
string t2 = "bbb";
string t3 = "ccc";
//10 strings
for (int i = 1; i<= 10; i++)
{
string key = "t" + i;
strLine = convertToFile(key);
f.WriteLine(strLine);
}
f.Close();
Like this all I get in the file is
t1
t2
t3
Upvotes: 0
Views: 318
Reputation: 61
If you are trying to convert a string (from a user input perhaps) to a local variable then you would be better using if or case.
for (int i = 1; i <= 10; i++)
{
string key = "t" + i;
if (key == "t1")
{
f.WriteLine(t1);
}
else if (key == "t2")
{
f.WriteLine(t2);
}
}
Or to build on Tim Schmelter's Answer
var t = new List<string>();
t.Add("aaa");
t.Add("bbb");
t.Add("ccc");
// ...
using (StreamWriter w = File.AppendText(path))
{
for (int i = 1; i <= 10; i++)
{
string key = "t"+i;
if (key == "t1")
{
w.WriteLine(t[1]);
}
else if (key == "t2")
{
w.WriteLine(t[2]);
}
}
}
Or without the string
for (int i = 1; i <= 10; i++)
{
w.WriteLine(t[i]);
}
Upvotes: 1
Reputation: 4507
The point is that you cannot access variables in the way your code outlines. What you do in the for loop is constructing the variable name you what to access. But you just generate a string that is named like your variables, but you cannot access them through a string. A variable in C# is a reference, the name you give it does not really matter. So all answers above solve your problem but you should carefully think about the result you expected from your code and why it does not work that way.
Upvotes: 1
Reputation: 6849
Simple as that
StringBuilder sb = new StringBuilder();
sb.AppendLine("aaa");
sb.AppendLine("bbb");
sb.AppendLine("ccc");
System.IO.File.WriteAllText("D:\fileName.txt", sb.ToString());
Upvotes: 1
Reputation: 460238
Use a collection instead of single variables:
var allStrings = new List<string>();
allStrings.Add("aaa");
allStrings.Add("bbb");
allStrings.Add("ccc");
// ...
using (StreamWriter w = File.AppendText(path))
{
foreach(string str in allStrings)
w.WriteLine(str );
}
or more concise using File.WriteAllLines
:
File.WriteAllLines(path, allStrings);
Upvotes: 3
Reputation: 23107
better store your strings in List<string>
and then use this method:
File.WriteAllLines(filePath, lines);
it will store your list of strings in file at filePath
to create list from your strings do:
var lines = new List<string>{ t1, t2, t3, t4, t5, t6, t7, t8, t9, t10};
Upvotes: 0