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(',');

```
You can improve on this pattern:

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

```

to avoid adding the comma in the first place:

```
string delimiter = "";
string writeUnEditedData = "";        
foreach (int s in connectionData)
{
    writeUnEditedData += $"{delimiter}{s}";
    delimiter = ",";
}

```

or with a `StringBuilder`... though contrary to popular belief this only helps if the `connectionData` collection is kinda big:

```
string delimiter = "";
var writeUnEditedData = new StringBuilder();        
foreach (int s in connectionData)
{
    writeUnEditedData.Append(delimiter).Append(s);
    delimiter = ",";
}

```

Even better still, stream the whole thing, to avoid needing all that extra memory and processing:

```
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
using (var sw = new StreamWriter(fileName2, true))
{
    for (int z = 0; z <= totalNumberOfCaves; z++)
    {
        string delimiter = "";
        for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
        {
            sw.Write(delimiter);
            sw.Write(connectionStack.Pop());
            delimiter = ",";
        }
        sw.Write(Environment.NewLine);
    }
}

```