我正在尝试生成文件名, log.txt的 log1.txt log2.txt 等
int filenum = 0;
public static void Maker()
{
string basename = "log";
string extention = ".txt";
string finalname = "log.txt";
for (int i = 0; i < 300; i++)
{
using (StreamWriter writer = new StreamWriter(workingDIR + finalname, true))
{
// addadder(filenum);
StringBuilder builder = new StringBuilder();
builder.Append(base);
builder.Append(filenum);
builder.Append(extension);
finalname = builder.ToString();
} }
}
有没有更好的方法来创建这些类型的文件? 第一个文件中没有数字EI log.txt 感谢
答案 0 :(得分:4)
您可以替换所有这些:
StringBuilder builder = new StringBuilder();
builder.Append(base);
builder.Append(filenum);
builder.Append(extension);
finalname = builder.ToString();
用这个:
finalname = string.Format("log{0}.txt", filenum);
或与此:
finalname = string.Format("{0}{1}{2}", basename, filenum, extension);
答案 1 :(得分:2)
要构建文件名,您可以使用字符串格式:
finalname = string.Format("log{0}.txt", (i + 1));
然后构建文件名,你应该使用System.IO命名空间中的Path.Combine
using(StreamWriter writer = new StreamWriter(Path.Combine(workingDir, finalname), true))
{
答案 2 :(得分:1)
string basename = "log";
string extention = ".txt";
for (int i = 0; i < 300; i++)
{
using(var writer = new StreamWriter(Path.Combine(
workingDir, string.Format("{0}{1:000}{2}" basename, i, extension), true))
{
// write file content using writer
}
}
答案 3 :(得分:0)
您可以使用:
const string basename = "log";
const string extention = ".txt";
IEnumerable<string> fileNames = Enumerable.Range(0, 300).
Select(index => string.Format("{0}{1}.{2}", basename, index, extension));
生成文件名序列
答案 4 :(得分:0)
这是你在找什么?
string fileName = "log.txt";
int count = 0;
if (File.Exists(fileName))
{
fileName = fileName + "(" + count.ToString() + ").txt";
count++;
}
else
{
//Add your logic here
File.Create(fileName);
}
答案 5 :(得分:0)
public static void Maker()
{
string basename = "log";
string extention = ".txt";
string finalname = "log.txt";
for (int i = 0; i < 300; i++)
{
using (StreamWriter writer = new StreamWriter(workingDIR + finalname, true))
{
if(i == 0)
{
finalname = basename + extention;
}
else
{
finalname = basename + i + extention;
}
}
}
}