我想要这样的文件名:Nr [文件中的第一个数字] - [文件中的最后一个数字] .txt。
我有:
static void Main(string[] args)
{
const int linesPerFile = 10;
string path = @"G:\Folder";
const string destinationFileName = @"G:\Folder\File-Part-{0}.txt";
var bans = BankAcoutNumbers.BANS;
string tempFile;
//string fileName = "File";
var maxNumberOfFiles = 10;
Stopwatch timer = new Stopwatch();
var fileCounter = 0;
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
var destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
try
{
// foreach (var bank in BankAcoutNumbers.BANS.Take(100))
//{
var lineCounter = 0;
string line;
while (fileCounter <= maxNumberOfFiles)
{
timer.Start();
foreach (var bank in BankAcoutNumbers.BANS.Take(100))
{
if (lineCounter % linesPerFile == 0)
{
//lineCounter = 0;
destiNationFile.Flush();
destiNationFile.Dispose();
destiNationFile = new StreamWriter(string.Format(destinationFileName, fileCounter + 1));
fileCounter++;
}
destiNationFile.WriteLine(bank);
lineCounter++;
}
fileCounter++;
//}
}
timer.Stop();
// Console.WriteLine(BankAcoutNumbers.BANS.Count());
Console.WriteLine(timer.Elapsed.Seconds);
}
catch (Exception)
{
throw;
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
所以第一个文件包含数字:
100000002 100000010 100000029 100000037 100000045 100000053 100000061 100000088 100000096 100000118
所以文件名必须是:Nr [100000002] - [100000118] .txt
谢谢
和第二个文件包含数字:
100000126 100000134 100000142 100000150 100000169 100000177 100000185 100000193 100000207 100000215
答案 0 :(得分:0)
除非您的文件很长,否则您只需将完整内容读入内存,拆分内容并重命名即可。
// Get files
DirectoryInfo di = new DirectoryInfo (@"c:\my\path");
var files = di.GetFiles();
// Loop through files
foreach (var file in files)
{
// Read file
string content = File.ReadAllText (file.FullName);
// Split text (add as many separators as you want, I'm using
// whitespace just like in your example)
string[] numbers = content.Split (' ');
// First number is numbers[0]
// Last number is numbers[numbers.Length - 1]
// Rename file
File.Move(file.FullName, string.Format("Nr{0}-{1}.txt", numbers[0], numbers[numbers.Length - 1]));
}