Reputation: 139
i'm working on win form application deals with XML files
i added this code to the form load event
if (!File.Exists("clients.xml"))
{
List<string> lines = new List<string>();
lines.Add("<clients>");
lines.Add("</clients>");
File.WriteAllLines("clients.xml", lines);
}
else if (!File.Exists("cases.xml"))
{
List<string> lines = new List<string>();
lines.Add("<names>");
lines.Add("</names>");
File.WriteAllLines("cases.xml", lines);
}
else if (!File.Exists("files.xml"))
{
List<string> lines = new List<string>();
lines.Add("<num>");
lines.Add("</num>");
File.WriteAllLines("files.xml", lines);
}
when i start my application if none of these three files exists it only creates the first file!!
if the first file only exists it creates only the second file !!
if both exists then it creates the third one..
any idea what is wrong with this code?!!
thanks ...
Upvotes: 0
Views: 103
Reputation: 9396
Do not do by the way you are doing:
Rule of thumb: Do not repeat the code
Write a generic function like this:
public void DoStuff(string fileName, List<string> linesToBeWritten)
{
var output = new List<string>();
if (!File.Exists(fileName))
return;
output.Add("<" + fileName + ">");
output.AddRange(linesToBeWritten);
output.Add("</" + fileName + ">");
File.WriteAllLines(fileName, output);
}
Upvotes: 2
Reputation: 13630
Remove the else
from the else if
.
This means that all of the if
statements will be evaluated.
The way that you have it set up, it has a waterfall effect. If the first statement is false, evaluate the second. If that is false evaluate the third etc.
Upvotes: 3
Reputation: 26209
Solution : use if
instead of else-if
.
Reason : if you use combination of if-else
it only executes first true
scenario and skips the further.
but if you use if
for all conditions it will execute all true
scenarios.
Code:
if (!File.Exists("clients.xml"))
{
List<string> lines = new List<string>();
lines.Add("<clients>");
lines.Add("</clients>");
File.WriteAllLines("clients.xml", lines);
}
if (!File.Exists("cases.xml"))
{
List<string> lines = new List<string>();
lines.Add("<names>");
lines.Add("</names>");
File.WriteAllLines("cases.xml", lines);
}
if (!File.Exists("files.xml"))
{
List<string> lines = new List<string>();
lines.Add("<num>");
lines.Add("</num>");
File.WriteAllLines("files.xml", lines);
}
else
{
return;
}
Upvotes: 4