Reputation: 2009
We are trying to read each word from a text file and replace it with another word. For smaller text files, it works well. But for larger text files we keep getting the exception: "String cannot be of zero length. Parameter name: oldValue "
void replace()
{
string s1 = " ", s2 = " ";
StreamReader streamReader;
streamReader = File.OpenText("C:\\sample.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";
// Console.WriteLine(s1);
// Console.WriteLine(s2);
streamWriter.Write(s1.Replace(s1,s2)); // Exception occurs here
}
else
break;
}
}
streamReader.Close();
streamWriter.Close();
}
we're unable to find the reason. Thanks in advance.
Upvotes: 3
Views: 13183
Reputation: 14326
The exception occurs because s1
is an empty string at some point. You can avoid this by replacing the line
String[] words = line.Split(delimiterChars);
with this:
String[] words = line.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
Upvotes: 5
Reputation: 108676
You want to change your Split method call like this:
String[] words = line.Split(delimiterChars,StringSplitOptions.RemoveEmptyEntries);
Upvotes: 4
Reputation: 499002
When you do your string.Split
you may get empty entries if there are multiple spaces or tabs in sequence. These can't be replaced as the strings are 0 length.
Use the overload that strips empty results using the StringSplitOptions
argument:
var words = line.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
Upvotes: 9
Reputation: 38179
It means that s1 contains an empty string ("") which can happen if you have two consecutive white spaces or tabs in your file.
Upvotes: 2