[英]Save .text file increment
我无法弄清楚为什么代码不能正常工作,当我点击保存按钮显示我Yokoso Log(1)然后第二个保存显示Yokoso Log(1).txt(2).txt .....
//Create txt and write
string logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Yokoso Log\\Yokoso Log");
TextWriter txtwrite = new StreamWriter(logPath);
int count = 1;
Find:
if (File.Exists(logPath))
{
logPath = logPath + "(" + count.ToString() + ").txt";
count++;
goto Find;
}
else
{
File.Create(logPath);
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
txtwrite.Write("\t" + dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t" + "|");
}
txtwrite.WriteLine("");
txtwrite.WriteLine("____________________________________________________________________");
}
txtwrite.Close();
MessageBox.Show("Log create successfully (directory desktop).");
}
}
你要做的是这样的事情:
var currentPath = logPath;
while (File.Exists(currentPath))
{
currentPath = logPath + "(" + count.ToString() + ").txt";
count++;
}
File.Create(currentPath);
...
在这里你要创建一个文件
TextWriter txtwrite = new StreamWriter(logPath);
然后,当你检查文件确定有一个文件
if (File.Exists(logPath))
这就是我认为你的意思
string logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Yokoso Log\\Yokoso Log");
int count = 1;
while (File.Exists(logPath))
{
logPath = logPath + "(" + count.ToString() + ").txt";
count++;
}
using (TextWriter txtwrite = new StreamWriter(logPath))
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
txtwrite.Write("\t" + dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t" + "|");
}
txtwrite.WriteLine("");
txtwrite.WriteLine("____________________________________________________________________");
}
}
MessageBox.Show("Log create successfully (directory desktop).");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.