我收到此错误未处理的类型' System.StackOverflowException'发生在mscorlib.dll 我知道你不应该有一个无限循环,但它不是一个无限循环,因为它只是去了它,直到它得到一个尚未制作的文件号。我怎样才能更好地解决这个问题?
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();
}
答案 0 :(得分: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
}