我想创建一个最多 400 行的 txt 文件。如果文本文件达到最大行数,则将创建一个具有不同名称的新文件,如果再次达到限制,情况相同。
我写了一个类“MaxLinesWriter”,但它运行起来很慢,不像原来的流光那样快。
有人可以帮帮我吗?
public class MaxLinesWriter
{
private int n = 0;
public int MaxLines;
public string NameFile;
private string ConstNameFile;
public int CounterOfLines;
DateTime date = new DateTime();
public MaxLinesWriter(string NameFileInput, int MaxLinesInput)
{
MaxLines = MaxLinesInput;
ConstNameFile = NameFileInput;
NameFile = ConstNameFile + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + date.Millisecond.ToString();
CounterOfLines = 0;
}
public void WriteLine(object StringToWrite)
{
if (CounterOfLines < MaxLines)
{
StreamWriter writer = new StreamWriter(NameFile + ".txt", true);
writer.WriteLine(StringToWrite);
CounterOfLines++;
writer.Close();
}
else
{
CounterOfLines = 1;
date = date.AddMilliseconds(1);
NameFile = ConstNameFile + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + date.Millisecond.ToString();
StreamWriter writer = new StreamWriter(NameFile + ".txt");
writer.WriteLine(StringToWrite);
writer.Close();
}
}
}
最佳答案
如果您在迭代中调用 WriteLine() 方法,则在迭代之外初始化 StreamWriter
:
public class MaxLinesWriter
{
private int n = 0;
public int MaxLines;
public string NameFile;
private string ConstNameFile;
public int CounterOfLines;
private StreamWriter writer;
DateTime date = new DateTime();
public MaxLinesWriter(string NameFileInput, int MaxLinesInput)
{
MaxLines = MaxLinesInput;
ConstNameFile = NameFileInput;
NameFile = ConstNameFile + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + date.Millisecond.ToString();
CounterOfLines = 0;
writer = new StreamWriter(NameFile + ".txt", true);
}
public void WriteLine(object StringToWrite)
{
if (CounterOfLines < MaxLines)
{
writer.WriteLine(StringToWrite);
CounterOfLines++;
}
else
{
writer.Close();
CounterOfLines = 1;
date = date.AddMilliseconds(1);
NameFile = ConstNameFile + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + date.Millisecond.ToString();
writer = new StreamWriter(NameFile + ".txt");
writer.WriteLine(StringToWrite);
}
}
// Call it after your last data
public void Close()
{
writer.Close();
}
}
关于c# - 具有最大行数的 Writer txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26714148/