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/']
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;
     ...

```
This usually means that the string is empty.

Try to put this guard code in:

```
string writeData = string.IsNullOrEmpty(writeUnEditedData)
    ? string.Empty
    : writeUnEditedData.Remove(writeUnEditedData.Length - 1);

```