[英]How to rename dynamically file name
我想要這樣的文件名: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 1000001
所以文件名必須是:Nr[100000002]-[100000118].txt
謝謝
第二個文件包含數字:
100000126 100000134 100000142 100000150 100000169 100000177 100000185 100000193 100000207 1000002
除非您的文件很長,否則您可以簡單地將它們的全部內容讀入內存,拆分它們的內容並重命名它們。
// 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]));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.