error when trying to remove last character of a string

  • A+
Category:Languages

I am trying to remove the last "," of a string however i am getting an error stating that

System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.

the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.

the code I am using is as follows

for (int z = 0; z <= totalNumberOfCaves; z++)     {         for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)         {             connectionData.Add(int.Parse(connectionStack.Pop()));         }         string fileName2 = @"D:/UNI/Year 5/AI - SET09122/SET09122 - CW1/WriteConnectionData.txt";         string writeUnEditedData = "";                 foreach (int s in connectionData)         {             writeUnEditedData += (s + ",");         }     using (StreamWriter sw = File.AppendText(fileName2))     {         string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);         sw.Write("{ " + writeData + " }," + Environment.NewLine);                 }     connectionData.Clear(); } 

 


Appending string in a loop:

    foreach (int s in connectionData)     {         writeUnEditedData += (s + ",");     } 

is not a good idea. Put Join:

    writeUnEditedData = string.Join(",", connectionData);  

Having this done, you don't have to remove anything:

 using (StreamWriter sw = File.AppendText(fileName2))  {       // No Remove here      string writeData = writeUnEditedData;      ... 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: