Englishman Englishman - 2 months ago 6x
C# Question

Duplication in csv reading

enter image description hereHope im alright posting this here if not let me know and ill remove asap. Im running into some problems in my code where when it reads the SQL file it duplicates entries and some times puts them in the wrong order. I've been stepping through my code and checking values but i haven't been able to find anything, there should only be 4 entries. any help would be much appreciated.

private void LoadBtn_Click(object sender, EventArgs e)
//Opens a browse box to allow the user to select which file, only CSV's allow allowed
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "CSV Files (*.csv)|*.csv";
openFileDialog1.FilterIndex = 1;

//empties text box when clicked | loads file location and name to load directory text box at top
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
ConvertedText.Text = string.Empty;
LoadDirectory.Text = openFileDialog1.FileName.ToString();
string filename = LoadDirectory.Text;
string[] Lines = File.ReadAllLines(filename);
string[] Fields;
string outfile = "";

for (int i = 1; i < Lines.Length; i++)
Fields = Lines[i].Split(new char[] { ',' });
outfile += "IF EXISITS (SELECT USERID FROM WUSERS WHERE USERID='" + Fields[0] + "')" + Environment.NewLine;
outfile += "begin" + Environment.NewLine;
}[![enter image description here][1]][1]


You never clear outfile between passes in the for loop.

Either declare

string outfile = "";

inside the loop or have

outfile = "";

at the very end of the loop