Jacob Lenertz
Jacob Lenertz

Reputation: 81

Getting a System.StackOverflowException' error

I am Getting this error An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll I know you are not supposed to have an infinite loop but its not an infinate loop because it just has too go till it gets a file number that has not been made yet. How can i go about this a better way?

private int x = 0;
public string clients = @"F:\Internal Jobs\Therm-Air Files\Program\P-1-2.0\Clients\";
public string tdate = DateTime.Today.ToString("MM-dd-yy");

public void saveloop()
{
    string path = LoadPO.Text.Substring(0, LoadPO.Text.LastIndexOf("\\"));
    string name = Path.GetFileName(path);
    string t = Convert.ToString(x);

    if (!File.Exists(path + @"\" + name + ".xlsx")) // This Line throws error
    {
        oSheet.SaveAs(path + @"\" + name + "-" + t + ".xlsx");
        string prop = /* snipped for space reasons, just string concats */

        string Combine = string.Empty;
        int b = 0;
        int c = cf.cPanel.Controls.Count;
        string[] items = new string[c];
        foreach (WProduct ewp in cf.cPanel.Controls)
        {
            string item = /* snipped for space reasons, just string concats */
            items[b] = item;
            b += 1;
        }
        Combine = prop + "^<";
        foreach (var strings in items)
        {
            Combine += strings + "<";
        }

        File.WriteAllText(path + @"\" + name + ".txt", Combine);
    }
    else
    {
        x += 1;
        saveloop();

    }

Upvotes: 0

Views: 1728

Answers (1)

Igor
Igor

Reputation: 62213

The reason the code above is failing is because you do not use i in the name of the file so you can increment all you want it does not change the name.

You need to abstract the creation of the name of the file from the code that does the writing. Think of it as writing code in blocks of functionality.

public static string GetFileName(string path, string name)
{
    var fileName = $@"{path}\{name}.xlsx";
    int i = 0;
    while (System.IO.File.Exists(fileName))
    {
        i++;
        fileName = $@"{path}\{name}({i}).xlsx";
    }
    return fileName;
}


public void saveloop()
{
    var fileName = GetFileName(path, name);
    // use fileName from this point on
}   

Upvotes: 2

Related Questions