需要帮助创建文件并在其上书写 [英] Need help in creating files and writing on it
本文介绍了需要帮助创建文件并在其上书写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好
Hi all
int lines = File.ReadAllLines(@"C:\ReportPrint.txt").Count();
if (lines > 50)
{
string path1 = @"C:\ReportPrint.txt";
string newFilePath = @"C:\ReportPrint_1.txt";
这是我用来检查文件中行数的代码,如果它更多然后50然后创建另一个文件。
工作正常。
但我想要的是假设行= 200
所以我将它除以50.因此代码应创建4个文件,如ReportPrint_1,ReportPrint_2等,并在每个文件上复制50行。
请告诉我怎么做。
this is the code i am using to checking the number of lines in a file and if it is more then 50 then create another file.
It's working fine.
But what i want is suppose lines=200
so i will divide it by 50. so the code should create 4 files like ReportPrint_1, ReportPrint_2 etc and copy 50 lines on each of them.
please tell me how to do this.
推荐答案
我确实喜欢这个
I did like this
public void splitfiles()
{
const string sourceFileName = @"C:\ReportPrint.txt";
const string destinationFileName = @"C:\ReportPrint-{0}.txt";
const int linesPerFile = 50;
using (var sourceFile = new StreamReader(sourceFileName))
{
var fileCounter = 0;
var destinationFile = new StreamWriter(
string.Format(destinationFileName, fileCounter + 1));
try
{
var lineCounter = 0;
string line;
while ((line = sourceFile.ReadLine()) != null)
{
// Did we reach the maximum number of lines for the file?
if (lineCounter >= linesPerFile)
{
// Yep... Time to close this one and
// switch to another file
lineCounter = 0;
fileCounter++;
destinationFile.Dispose();
destinationFile = new StreamWriter(
string.Format(destinationFileName, fileCounter + 1));
}
destinationFile.WriteLine(line);
lineCounter++;
}
}
finally
{
destinationFile.Dispose();
}
}
如果看起来不是一个好主意,但问题是什么?请看:
http ://msdn.microsoft.com/en-us/library/system.io.streamreader%28v=vs.110%29.aspx [ ^ ],
< a href =http://msdn.microsoft.com/en-us/library/system.io.streamwriter%28v=vs.110%29.aspx> http://msdn.microsoft.com/en-us /library/system.io.streamwriter%28v=vs.110%29.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline( v = vs.110).aspx [ ^ ],
http://msdn.microsoft.com/en -us / library / 7ack4zyt(v = vs.110).aspx [ ^ ]。
有什么问题吗? :-)
-SA
If does not look like a good idea, but what's the problem? Just see:
http://msdn.microsoft.com/en-us/library/system.io.streamreader%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.io.streamwriter%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/7ack4zyt(v=vs.110).aspx[^].
Any concerns? :-)
—SA
这篇关于需要帮助创建文件并在其上书写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文