【问题标题】:Getting a System.StackOverflowException' error收到 System.StackOverflowException' 错误
【发布时间】:2017-08-17 05:04:14
【问题描述】:

我收到此错误mscorlib.dll 中发生了“System.StackOverflowException”类型的未处理异常我知道您不应该有无限循环,但它不是无限循环,因为它只是直到它得到一个尚未制作的文件号。我怎样才能更好地解决这个问题?

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

    }

【问题讨论】:

  • 哪一行代码抛出堆栈溢出错误?
  • 我编辑了显示位置的代码
  • 您可能没有显示专门回答您的问题所需的所有代码。通常,此错误是由于方法内容中的某些内容导致该方法被递归调用的结果。例如,当更改事件发生时触发的方法,但方法中的代码更改了导致事件再次触发的事物,或者该方法显式调用自身,但未正确处理终止条件。 您应该包含此方法的标头,其中显示方法名称和签名
  • @JacobLenertz - 不,它没有。您的 LoC File.Exists(path + @"\" + name + ".xlsx")) 不使用变量 i
  • @JacobLenertz - 也许。问题是您的代码检查文件是否在最顶部退出,如果确实存在,它会进入 else 语句,该语句递增 i 并再次调用自身但您不使用 i 做任何事情,所以它会递归无限。

标签: c# forms visual-studio loops


【解决方案1】:

上面的代码失败的原因是你没有在文件名中使用i,所以你可以增加你想要的所有内容,它不会改变名称。

您需要从编写代码的代码中抽象出文件名的创建。把它想象成在功能块中编写代码。

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
}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2012-09-24
    • 2011-04-12
    • 2022-01-24
    • 2014-03-24
    相关资源
    最近更新 更多