Exception "String cannot be of Zero length"
Solution 1
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);
Solution 2
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);
Solution 3
You want to change your Split method call like this:
String[] words = line.Split(delimiterChars,StringSplitOptions.RemoveEmptyEntries);
Solution 4
It means that s1 contains an empty string ("") which can happen if you have two consecutive white spaces or tabs in your file.
vidya sagar
Updated on August 02, 2022Comments
-
vidya sagar almost 2 years
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.