计算 C# 中复制的文件数量
本文关键字:文件 复制 计算 | 更新日期: 2023-09-27 18:30:45
我有一个计算机列表,我正在将文件复制到其中。
我正在尝试创建一个标签,显示当时正在复制到哪台计算机。例如:"复制到计算机1...(x of 10)",其中 10 基于字符串数组中的行数:
var lineCount = File.ReadLines(complist).Count();
如何让每次复制新文件时更改第一个数字 (x)?(1 of 10), (2 of 10) 等等...
这是我的标签的样子:
label2.Text = ("Copying to " + @computer + "... ( of " + lineCount + ")");
编辑:这是我的复制操作。文件将复制到每个远程系统。
string complist = openFileDialog2.FileName;
string patch = textBox2.Text;
string fileName = patch;
string patchfile = Path.GetFileName(fileName);
var lineCount = File.ReadLines(complist).Count();
foreach (string line in File.ReadLines(complist))
{
//Checks if C:'PatchUpdates exists on remote machine. If not, a folder is created.
if (!Directory.Exists(@"''" + line + @"'C$'PatchUpdates"))
{
Directory.CreateDirectory(@"''" + line + @"'C$'PatchUpdates");
}
//XCOPY patch to every computer
System.Diagnostics.Process processCopy = new System.Diagnostics.Process();
ProcessStartInfo StartInfo = new ProcessStartInfo();
StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
StartInfo.FileName = "cmd";
StartInfo.Arguments = string.Format("/c xcopy " + patch + " " + @"''{0}'C$'PatchUpdates /K /Y", line);
processCopy.StartInfo = StartInfo;
processCopy.Start();
label2.Text = ("Copying to " + @line + "... (" + @num + " of " + @lineCount + ")");
processCopy.WaitForExit();
只需将num
声明为变量并在循环中递增它:
int num = 0;
foreach (string line in File.ReadLines(complist))
{
num++;
//...
label2.Text = ("Copying to " + line + "... (" + num + " of " + lineCount + ")");
//..
}
顺便说一下,您正在两次读取文件中的行。一旦你得到了行数,另一个时间得到行本身。
如果您有一个大文件并且不想一次读取所有行(出于内存问题),则最好使用 ReadLines
。但是,如果文件相对较小,则可以使用 ReadAllLines
读取文件行一次,并将它们存储在如下所示的变量中:
var lines = File.ReadAllLines(complist);
var lineCount = lines.Length;
int num = 0;
foreach (string line in lines)
{
num++;
//...
}
只需保留一个索引,每次转到下一行时都会增加该索引。
int num = 0;
foreach (string line in File.ReadLines(complist))
{
++num;
string progress = string.Format("Copying to {0} ({1} of {2})", line, num, lineCount);
// ...
我保留了您的变量名称,尽管我强烈建议使用比 line
和 num
(如 computerName
和 computerIndex
)更好的东西。
或者,你可以用一个老式的for
循环来替换foreach
,这基本上反转了整个事情:
var lines = File.ReadLines(complist);
for (int num = 0; num < lineCount; ++num)
{
string line = lines[num];
string progress = string.Format("Copying to {0} ({1} of {2})", line, num, lineCount);
// ...
for(int i = 0; i < lineCount; i ++)
{
label2.Text = string.Format(@"Copying to {0} ({1} of {2})", complist[i], i + 1, lineCount;
// Copy logic ...
}