we have a datatable “st” with two columns “word” and “binary”
void replace()
{
string s1="", s2="";
StreamReader streamReader;
streamReader = File.OpenText("C:\\text.txt");
StreamWriter streamWriter = File.CreateText("C:\\sample1.txt");
int x = st.Rows.Count;
// int i1 = 0;
// Now, read the entire file into a string
while ((line = streamReader.ReadLine()) != null)
{
for (int i = 0; i < x; i++)
{
s1 = Convert.ToString(st.Rows[i]["Word"]);
s2 = Convert.ToString(st.Rows[i]["Binary"]);
s2+="000";
char[] delimiterChars = { ' ', '\t' };
String[] words = line.Split(delimiterChars);
// Write the modification into the same file
String ab = words[i]; //exception occurs here
// Console.WriteLine(ab);
streamWriter.Write(ab.Replace(s1,s2));
}
}
streamReader.Close();
streamWriter.Close();
}
we’re getting an “Index was outside the bounds of the array” exception. we’re unable to find the problem. thanks in advance
EDIT:
tnx to everyone who helped.
i did this and it worked somehow:
void replace()
{
string s1 = "", s2 = "";
StreamReader streamReader;
streamReader = File.OpenText("C:\\sample1.txt");
StreamWriter streamWriter = File.CreateText("C:\\sample1.txt");
int x = st.Rows.Count;
while ((line = streamReader.ReadLine()) != null)
{
char[] delimiterChars = { ' ', '\t' };
String[] words = line.Split(delimiterChars);
foreach (string str in words)
{
s1 = str;
DataRow drow = st.Rows.Find(str);
if (drow != null)
{
index = st.Rows.IndexOf(drow);
s2 = Convert.ToString(st.Rows[index]["Binary"]);
// s2 += "000";
// ab = words[i];
Console.WriteLine(s1);
Console.WriteLine(s2);
streamWriter.Write(str.Replace(s1, s2));
}
else
break;
}
}
streamReader.Close();
streamWriter.Close();
}
tnx to everyone once again.
regards,
sagar
If you have a hypothetical line “a b c d e” for instance the first line in your file, and your database “st” contains 10 rows, you would loop through the process 10 times, on the 6th time you would encounter the error. The 6th step would split the string into: {a, b, c, d, e} and then attempt to get the 5th index (zero based), which would be outside of the array.