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();
}

```
['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/']
Try `string.TrimEnd()`:

```
writeUnEditedData = writeUnEditedData.TrimEnd(',');

```
Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0.